中序线索化二叉树

本文介绍了一个使用C++实现的中序线索二叉树遍历算法。该算法首先构建一棵二叉树,然后对其进行中序线索化处理,最后通过遍历中序线索树来输出与普通二叉树中序遍历相同的节点序列。
#include<stdio.h>//A R # T # # Y E # # #
#include<iostream>
using namespace std;

struct threadnode
{
    char v;
    int ltag,rtag;
    threadnode*ls,*rs;

};
// 定义pre为全局变量可以
class threadbitree
{
    private:
        threadnode*root; //指向中序化线索二叉树根节点的指针
        threadnode*pre;  //指向上一次访问的节点
    public:
        threadbitree()//构造函数
        {
            pre=NULL;
            root=creat();//建立一棵二叉树
            cout<<"/中序线索化遍历:"<<endl;
            inthread(root);//把root指针指向的树中序线索化
            inorder();//把中序线索树遍历一遍,输出结果和二叉树的中序遍历结果相同
        }
        ~threadbitree()//析构函数
        {

        }
        threadnode*next(threadnode*p)//查找p的后继
        {
            struct threadnode*q;
            if(p->rtag==1)
                q=p->rs;
            else
            {
                q=p->rs;
                while(q->ltag==0)
                    q=q->ls;
            }
            return q;

        }

        void inorder()
        {
            struct threadnode*p;
            if(root==NULL) return ;
            p=root;
            while(p->ltag==0)
                p=p->ls;
            cout<<p->v<<" ";
            while(p->rs!=NULL)
            {
                p=next(p);
                cout<<p->v<<" ";
            }


        }


    private:
            threadnode*creat()
            {
                char ch;
                cin>>ch;
                if(ch=='#')
                    return NULL;
                struct threadnode*p=new threadnode;
                p->v=ch;
                p->ltag=p->rtag=0;
                p->ls=creat();
                p->rs=creat();
                return p;
            }
            void inthread(threadnode*now)
            {
                if(now==NULL) return ;
                inthread(now->ls);
                if(now->ls==NULL)
                {
                    now->ltag=1;
                    now->ls=pre;
                }
                if(now->rs==NULL)
                {
                    now->rtag=1;
                }
                if(pre!=NULL&&pre->rtag==1)
                {
                    pre->rs=now;
                }
                pre=now;
                inthread(pre->rs);

            }
};

int main()
{
    threadbitree t;
    return 0;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值