zoukankan      html  css  js  c++  java
  • 中序线索化二叉树

    #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;
    
    }
    

  • 相关阅读:
    C++疑难杂症
    程序中的错误、异常处理框架设计
    客户端ARPG角色行为模型
    http协议
    MySQL数据库开发(2)
    MySQL数据库开发(1)
    网络编程进阶及并发编程
    网络编程-SOCKET开发
    面向对象编程
    常用模块
  • 原文地址:https://www.cnblogs.com/eason9906/p/11755125.html
Copyright © 2011-2022 走看看