线索二叉树 (C++实现)

  • 线索二叉树就是在原有的二叉树上添加了两个tag属性,用来记录当前节点的线索
  • 如果ltag=0 lchild指向节点的左孩子
  • 如果ltag=1 lchild指向节点的前驱节点
  • 如果rtag=0 rchild指向节点的右孩子
  • 如果rtag=1 rchild指向节点的后继节点

因为先、中、后序的前驱跟后继节点会有区别,所以二叉树线索化需要分为三种序列的线索二叉树,这里以后序为例

typedef int datatype;

typedef struct BiThrNode{
    
    
    datatype data;
    BiThrNode *lchild,*rchild;
    unsigned ltag,rtag;
}BiThrNode,*BiThrTree;

BiThrTree pre=nullptr;

BiThrTree PostOrderThr(BiThrNode *p,BiThrNode *&pre){
    
       //后序线索二叉树
    if(p){
    
    
        PostOrderThr(p->lchild,pre);
        PostOrderThr(p->rchild,pre);
        if(p->lchild==nullptr){
    
    
            p->lchild=pre;
            p->ltag=1;
        }
        if(pre!=nullptr&&pre->rchild==nullptr){
    
    
            pre->rchild=p;
            pre->rtag=1;
        }
        pre=p;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_43477024/article/details/109754627