穿线二叉树

#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
typedef char type;
typedef struct node
{
    type data;
    int ltag,rtag;
    struct node *lchild,*rchild;
}binthrnode;
typedef binthrnode *binthrtree;
binthrtree pre=NULL;
//前序遍历创建一棵二叉树
binthrtree createbintree()
{
    char ch;
    binthrtree t;
    if((ch=getchar())=='#')
        t=NULL;
    else
    {
        t=(binthrnode*)malloc(sizeof(binthrnode));
        t->data=ch;
        t->lchild=createbintree();
        t->rchild=createbintree();
    }
    return t;
}
//将普通二叉树进行中序线索化
void inthreading(binthrtree *p)
{
    if(*p)
    {
        inthreading(&(*p)->lchild);//中序线索化左子树
        (*p)->ltag=((*p)->lchild)?0:1;//根据左子树调整左标记
        (*p)->rtag=((*p)->rchild)?0:1;//根据右子树调整右标记
        if(pre)//如果存在前驱
        {
            if(pre->rtag==1)pre->rchild=*p;
            //如果前驱的右子树不存在,则将其右指针连接到当前树
            if((*p)->ltag==1)(*p)->lchild=pre;
            //如果当前树的左子树不存在,则将当前树的左指针指向前驱
        }
        pre=*p;//更新前驱
        inthreading(&(*p)->rchild);//中序线索化右子树
    }
}
//创建中序穿线二叉树
void createthrtree(binthrtree *p)
{
    *p=createbintree();
    inthreading(p);
}
//求中序遍历线索二叉树中节点p的后继节点
binthrtree insuccnode(binthrtree p)
{
    binthrtree q;
    if(p->rtag==1)//如果正好存在后继位置,则返回后继
        return p->rchild;
    else
    {
        q=p->rchild;//按照中序遍历顺序,当前节点的后继应该为
                    //其右子树的最左下的节点
        while(q->ltag==0)
            q=q->lchild;
        return q;
    }
}
void inthrtree(binthrtree p)
{
    if(p)
    {
        while(p->ltag==0)//找到中序遍历下第一个节点
                        //即:最左下位置
            p=p->lchild;
        do
        {
            printf("%d
",p->data);
            p=insuccnode(p);//循环它的后继节点
        }
        while(p);
    }
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

原文地址:https://www.cnblogs.com/Thereisnospon/p/4768510.html