线索二叉树的实现


#include <stdio.h>
#include <stdlib.h>

typedef char elemtype;
//线索储存标志位
//link(0)表示指向左右孩子的指针
//link(1)表示指向前驱后继的线索
typedef enum {link,thread}pointertag;

typedef struct bithrnode{
    char data;
    struct bithrnode *lchild,*rchild;
    pointertag ltag;
    pointertag rtag;
}Bithrnode,*Bithrtree;

//全局变量,始终指向刚刚访问过的节点
Bithrtree pre;

//创建一棵二叉树,约定用户遵照前序遍历的方式输入数据

void createbithrtree(Bithrtree *t){
    char c;
    scanf("%c",&c);
    if(c==' '){
        (*t)=NULL;
    }
    else {
        (*t)=(Bithrnode *)malloc(sizeof(Bithrnode));
        (*t)->data=c;
        (*t)->ltag=link;
        (*t)->rtag=link;
        createbithrtree(&(*t)->lchild);
        createbithrtree(&(*t)->rchild);
    }
}

void inthreading(Bithrtree t){
    if(t){
        inthreading(t->lchild);     //递归左孩子线索化
        //节点处理
        if(!t->lchild){//如果该节点没有左孩子,设置ltag为thread并把lchild指向刚刚访问过的节点
            t->ltag=thread;
            t->lchild=pre;
        }
        if(!pre->rchild){
            pre->rtag=thread;
            pre->rchild=t;
        }
        pre=t;
        inthreading(t->rchild);     //递归右孩子线索化
    }
}

void inorderthreading(Bithrtree *p,Bithrtree t){
    *p=(Bithrnode *)malloc(sizeof(Bithrnode));
    (*p)->ltag=link;
    (*p)->rtag=thread;
    (*p)->rchild=(*p);
    if(!t){
        (*p)->lchild=*p;
        pre=*p;
        inthreading(t);
        pre->rchild=*p;
        pre->rtag=thread;
        (*p)->rchild=pre;
    }
}

int main()
{
    Bithrtree p,t=NULL;
    createbithrtree(&t);
    inorderthreading(&p,t);
    return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值