线索化二叉树,编译时程序异常退出
#include <stdio.h>#include <stdlib.h>
typedef struct Tree
{
int data,Ltag,Rtag;
struct Tree *LChild,*RChild;
}Tree,*Trees;
void CreateTree(Trees *boot)//创建二叉树,具体操作参考上一篇《树与二叉树》
{
int ch;
scanf("%d",&ch);
if(ch==0)
*boot=NULL;
else
{
*boot=(Trees)malloc(sizeof(Tree));
(*boot)->data=ch;
(*boot)->LChild=(*boot)->RChild=NULL;
(*boot)->Ltag=(*boot)->Rtag=0;
CreateTree(&((*boot)->LChild));
CreateTree(&((*boot)->RChild));
}
}
//添加线索
void InThread(Trees boot)
{
Trees pre=NULL;
if(boot)
{
InThread(boot->LChild);
if(boot->LChild==NULL)
{
boot->Ltag=1;
boot->LChild=pre;
}
if(pre!=NULL&&boot->RChild==NULL)
{
pre->RChild=boot;
pre->Rtag=1;
}
pre=boot;
InThread(boot->RChild);
}
}
//中序找前驱
Tree *InPre(Trees boot)
{
Trees pre=NULL,q=NULL;
if(boot->Ltag==1)
pre=boot->LChild;
else
{
for(q=boot->LChild;q->Rtag==0;q=q->RChild)
pre=q;
}
return pre;
}
//中序找后继
Tree *InNext(Trees boot)
{
Trees Next=NULL,q=NULL;
if(boot->Rtag==1)
Next=boot->RChild;
else
{
for(q=boot->RChild;q->Ltag==0;q=q->LChild)
Next=q;
}
return Next;
}
//中序遍历序线索树上的第一个结点
Tree *InFirst(Trees boot)
{
Trees p=boot;
if(!p)
return NULL;
while(p->Ltag==0)
p=p->LChild;
return p;
}
//中序遍历线索二叉树
void TInOrder(Trees boot)
{
Trees p;
p=InFirst(boot);
while(p)
{
printf("%2d",p->data);
p=InNext(p);
}
printf("\n");
}
int main()
{
Trees boot=NULL;
printf("创建二叉树,输入零结束:\n");
CreateTree(&boot);
InThread(boot);
Trees temp=NULL;
temp=InPre(boot);
printf("中序找到的前驱为:\n",temp->data);
Trees temp1=InNext(boot);
printf("中序找到的后继为:\n",temp1->data);
Trees bt=InFirst(boot);
printf("中序遍历序线索树上的第一个结点为:\n",bt->data);
TInOrder(bt);
free(boot);
free(temp);
free(temp1);
free(bt);
return 0;
}
创建二叉树时:
样例输入:1(根结点)2(左子树)0(结束左子树的左孩子输入)0(结束左子树的右孩子)输入...以此类推