#include <stdio.h>
#include <stdlib.h>
typedef char Element;
//0代表孩子节点,1代表线索
enum PointerTag { Link,Thread };
typedef struct BiThrNdoe
{
Element date;
PointerTag ltag,rtag;
BiThrNdoe* lchild;
BiThrNdoe* rchild;
}BiThrNdoe,*BiThrTree;
BiThrTree pre;
//前序创建二叉树
void CreateBiThrTree(BiThrTree *T)
{
char c;
scanf("%c",&c);
if(' '==c)
{
*T=NULL;
}
else
{
*T=(BiThrNdoe *)malloc(sizeof(BiThrNdoe ));
(*T)->date=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))
{
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=(BiThrTree)malloc(sizeof(BiThrNdoe));
(*p)->ltag=Link;
(*p)->rtag=Thread;
(*p)->rchild=*p;
if(!T)
{
(*p)->lchild=*p;
}
else
{
(*p)->lchild=T;
pre=*p;
InThreading(T);
pre->rchild=*p;
pre->rtag=Thread;
(*p)->rchild=pre;
}
}
//打印
void Visit(char c)
{
printf("%c ",c);
}
//中序遍历
void InOrderTraverse(BiThrTree T)
{
BiThrTree p;
p=T->lchild;
while(p!=T)
{
while(p->ltag==Link)
{
p=p->lchild;
}
Visit(p->date);
if(p->rtag==Thread && p->rchild !=T)
{
p=p->rchild;
Visit(p->date);
}
p=p->rchild;
}
}
int main()
{
BiThrTree P,T=NULL;
CreateBiThrTree(&T);
InOrderThreading(&P,T);
printf("中序遍历结果为:");
InOrderTraverse(P);
printf("\n");
return 0;
}
线索化二叉树
最新推荐文章于 2022-08-27 12:43:03 发布