中序线索化二叉树

#include <stdio.h>

#include <stdlib.h>

typedef char TElemType;

typedef enum {Link,Thread} pointertag;

typedef struct TBTNode TBTNode;//结构体类型

typedef TBTNode *BiThrTree;//结构体指针类型

struct TBTNode

{

    TElemType data;

    BiThrTree lchild;

    BiThrTree rchild;

    pointertag ltag;

    pointertag rtag;

};

BiThrTree CreateBiThrTree(BiThrTree T);//创建普通树

BiThrTree CreateThread(TBTNode *b);//对创建好的二叉树进行线索化

void Thead(TBTNode *p);//递归线索化

void ThInOrder(TBTNode *tb);//以找线索的方式中序遍历


void Print(BiThrTree T);//正常的中序遍历


BiThrTree pre;//全局变量,指向上一个访问的节点,用来在线索化的时候记录前驱的

int main()

{

    BiThrTree T = NULL;

    T = CreateBiThrTree(T);

    /*创建树的测试用例:ABC##DE#G##F### 就是书上131页算法6.3那里的测试数据,树的图在127页左下角*/

    BiThrTree Th = CreateThread(T);

    ThInOrder(Th);

    return 0;

}

BiThrTree CreateBiThrTree(BiThrTree T)

{

    TElemType ch;

    scanf("%c",&ch);

    if(ch=='#')

    {

        return NULL;

    }

    else

    {

        T=(TBTNode *)malloc(sizeof(TBTNode));

        T->data = ch;

        T->ltag = T->rtag = Link;

        T->lchild = CreateBiThrTree(T->lchild);

        T->rchild = CreateBiThrTree(T->rchild);

        return T;

    }

}

BiThrTree CreateThread(TBTNode *b)

{

    TBTNode *root;

    root=(TBTNode *)malloc(sizeof(TBTNode));

    root->ltag=Link;

    root->rtag=Thread;

    root->rchild=b;

    if(b==NULL) root->lchild=root;

    else

    {

        root->lchild=b;

        pre=root;

        Thead(b);

        pre->rchild=root;

        pre->rtag=Thread; //你这里打成了ltag,调试了好久。。。

        root->rchild=pre;

    }

    return root;

}

void Thead(TBTNode *p)

{

    if(p!=NULL)

    {

        Thead(p->lchild);

        if(p->lchild==NULL)

        {

            p->lchild=pre;

            p->ltag=Thread;

        }

        else p->ltag=Link;

        if(pre->rchild==NULL)

        {

            pre->rchild=p;

            pre->rtag=Thread;

        }

        else pre->rtag=Link;

        pre=p;

        Thead(p->rchild);

    }

}

void ThInOrder(TBTNode *tb)

{

    TBTNode *p=tb->lchild;

    while(p!=tb)

    {

        while(p->ltag==Link) p=p->lchild;

        printf("%c ",p->data);

        while(p->rtag==Thread&&p->rchild!=tb)

        {

            p=p->rchild;

            printf("%c ",p->data);

            

        }

        p=p->rchild;

    }

}

void Print(BiThrTree T)

{

    if (T) {

        Print(T->lchild);

        printf("%c",T->data);

        Print(T->rchild);

    }

}


  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值