线索化二叉树

先序序列:abc,,de,g,,f,,,

线索化输出:cbegdfa

#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
    char ch;
    struct node *lc;
    struct node *rc;
    int ltag;
    int rtag;
}BiTree;
BiTree *pre;//设置前一结点指针
BiTree *creat(BiTree *root)
{
    char c;
    scanf("%c",&c);
    if(c==',') root=NULL;
    else
    {
        root=(BiTree *)malloc(sizeof(BiTree));
        root->ch=c;
        root->ltag=0;
        root->rtag=0;//该结点既有左孩子,也有右孩子
        root->lc=creat(root->lc);
        root->rc=creat(root->rc);
    }
    return (root);
}
void InThreading(BiTree *root)
{
    if(root!=NULL)//若二叉树不空
    {
        InThreading(root->lc);//线索化左子树
        if(root->lc==NULL)
        {
            root->ltag=1;
            root->lc=pre;
        }//该结点左子树为空时,左标志置为1,指向其上一结点
        if(pre->rc==NULL)
        {
            pre->rtag=1;
            pre->rc=root;
        }//若该结点右子树为空时,右标志置为1,上一结点的右孩子指向该结点
        pre=root;//最后,上一结点指向该结点
        InThreading(root->rc);//线索化右子树
    }
}
void InOrderThreading(BiTree *p,BiTree *root)
{
    p=(BiTree *)malloc(sizeof(BiTree));
    p->ltag=0;
    p->rtag=1;
    p->rc=p;
    if(root==NULL) p->lc=p;
    else
    {
        p->lc=root;
        pre=p;
        InThreading(root);
        pre->rc=p;
        pre->rtag=1;
        p->rc=pre;
    }
}
void print(BiTree *root)
{
    BiTree *p;
    p=root->lc;
    while(p!=root)
    {
        while(p->ltag!=1) p=p->lc;//一直找到最右边的结点
        printf("%c",p->ch);
        while(p->rtag==1&&p->rc!=root)
        {
            p=p->rc;
            printf("%c",p->ch);
        }//遍历左子树
        p=p->rc;//遍历右子树
    }
    printf("%c",p->ch);
}
int main()
{
    BiTree *root,p;
    root=(BiTree *)malloc(sizeof(BiTree));
    root=creat(root);
    InOrderThreading(&p,root);
    printf("中序遍历结果为:\n");
    print(root);
    printf("\n");
    return 0;
}
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值