创建一个二叉树,对该树线索化,对该树线索化遍历

//首先创建一个二叉树,对该树线索化,对该树线索化遍历
#include<stdio.h>
#include<malloc.h>
#define ElemType char
typedef enum tag{link,thread};
 
typedef struct threadtree
{
 ElemType data;
 struct threadtree *lchild,*rchild;
 tag ltag,rtag;
}threadtree,*sthreadtree;

//全局变量
sthreadtree pre;

//建立二叉树,类似先序遍历
void creat(sthreadtree &t)
{
 char ch;
   scanf("%c",&ch);
   if(ch=='#')
    t=NULL;
   else
   {
    t=(sthreadtree)malloc(sizeof(threadtree));
    t->data=ch;
    t->ltag=link;t->rtag=link;
    creat(t->lchild);
    creat(t->rchild);
   }
}

//中序遍历
void mid(sthreadtree t)
{
 if(t)
 {
  mid(t->lchild);
  printf("%c",t->data);
  mid(t->rchild);
 }
}

//线索化二叉树,类似中序遍历
void InThread(sthreadtree t)
{

 if(t)
 {
        InThread(t->lchild);
  if(!t->lchild) {t->ltag=thread;t->lchild=pre;}
  if(!pre->rchild) {pre->rtag=thread;pre->rchild=t;}
  pre=t;
  InThread(t->rchild);
 }
}

//添加一个头结点
void InorderThread(sthreadtree &head,sthreadtree t)
{
 //sthreadtree pre;
 head=(sthreadtree)malloc(sizeof(threadtree));
 head->ltag=link;head->rtag=thread;
 head->rchild=head;
 if(!t) head->lchild=head;
 else
 {
  head->lchild=t;pre=head;
  InThread(t);
  pre->rchild=head;pre->rtag=thread;
  head->rchild=pre;
 }
}

//线索化遍历二叉树
void InOrderTraverse(sthreadtree t)
{
 sthreadtree p;
 p=t->lchild;
 while(p!=t)
 {
  while(p->ltag==link) p=p->lchild;
  printf("%c",p->data);
  while(p->rtag==thread&&p->rchild!=t)
  {
   p=p->rchild;
   printf("%c",p->data);
  }
  p=p->rchild;
 }
}


void main()
{
 sthreadtree t=NULL;
    sthreadtree T=NULL;//head
    printf("请输入要建立树的序列:/n");
 creat(t);//mid(t);printf("/n");
 InorderThread(T,t);
 InOrderTraverse(T);
 printf("/n");
}
/*
请输入要建立树的序列:
HDA##C#B##GF#E###
ADCBHFEG
Press any key to continue
*/ 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值