[转载] 线索二叉树的实现

输入                                   A

                           B                          C

                D               E           F             G

          H        I       J

以先序遍历,用“#”表示为空,输入ABDH##I##EJ###CF##G##

参考代码

#include <stdio.h>
#include <malloc.h>

typedef enum{Link,Thread} PointerTag;  /*指针标志*/

typedef char DataType;

typedef struct BiThreTree
{  /*定义结点元素*/
    PointerTag LTag,RTag;
    DataType data;
	struct BiThreTree *lchild,*rchild;
}BiThreTree;

BiThreTree *pre;                   /*全局变量,用于二叉树的线索化*/

BiThreTree *CreateTree()            /*按前序输入建立二叉树*/
{
    BiThreTree *T;
    DataType ch;
    scanf("%c",&ch);
    if(ch=='#')
      T=NULL;
    else
    {
	    T=(BiThreTree *)malloc(sizeof(BiThreTree));
        T->data=ch;
        T->LTag=Link;          /*初始化时指针标志均为Link*/
        T->RTag=Link;
        T->lchild=CreateTree();
        T->rchild=CreateTree();
    }
    return T;
}

void InThread(BiThreTree *T)
{
    BiThreTree *p;
    p=T;
    if(p)
    {
         InThread(p->lchild);
         if(!p->lchild)
		 { 
		      p->LTag=Thread;
              p->lchild=pre;
         }
         if(!pre->rchild)
         {
		      pre->RTag=Thread;
              pre->rchild=p;

        }
        pre=p;
        InThread(p->rchild);
     }
}

BiThreTree *InOrderThrTree(BiThreTree *T) /*中序线索化二叉树*/
{
     BiThreTree *Thre;                 /*Thre为头结点的指针*/
     Thre=(BiThreTree *)malloc(sizeof(BiThreTree));
     Thre->lchild=T;
     Thre->rchild=Thre;
     pre=Thre;
     InThread(T);
     pre->RTag=Thread;
     pre->rchild=Thre;
     Thre->rchild=pre;
     return Thre;
}

void InThrTravel(BiThreTree *Thre)    /*中序遍历二叉树*/
{
     BiThreTree *p;
     p=Thre->lchild;
     while(p!=Thre)                  /*指针回指向头结点时结束*/
     {
         while(p->LTag==Link)
         p=p->lchild;
         printf("%c ",p->data);
         while(p->RTag==Thread&&p->rchild!=Thre)
         {
		     p=p->rchild;
             printf("%c ",p->data);
         }
         p=p->rchild;
     }
}

int main()
{
    BiThreTree *T,*Thre;
    T=CreateTree();
    Thre=InOrderThrTree(T);
    InThrTravel(Thre);
    system("pause");
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值