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

  • 相关阅读:
    重新学习MySQL数据库开篇:数据库的前世今生
    Java网络编程和NIO详解9:基于NIO的网络编程框架Netty
    测试小鲸鱼
    golang
    技术篇
    请求报文和响应报文
    编程
    测试
    PHP
    centos7.1 从源码升级安装Python3.5.2
  • 原文地址:https://www.cnblogs.com/eason9906/p/11755126.html
Copyright © 2011-2022 走看看