#include<iostream>
using namespace std;
//线索标志,链表标志
typedef enum Flag
{
Link,
Thread
}TFlag;
//线索二叉树
typedef struct BiThrNode
{
char data;
struct BiThrNode *LChild,*RChild;
TFlag LFlag,RFlag;
} BiThrTNode,*BiThrTree;
BiThrTree pre;
//中序线索化
void InThreading(BiThrTree p,BiThrTree &pre)
{
if (p)
{
InThreading(p->LChild,pre);
if (!p->LChild)
{
p->LFlag=Thread;
p->LChild=pre;
}
if (!pre->RChild)
{
pre->RFlag=Thread;
pre->RChild=p;
}
pre=p;
InThreading(p->RChild,pre);
}
}
//线索化二叉树
bool InOrderThreading(BiThrTree &Thrt,BiThrTree T)
{
BiThrTree pre;
if (!(Thrt=(BiThrTree)malloc(sizeof(BiThrTNode))))
return false;
Thrt->LFlag=Link;
Thrt->RFlag=Thread;
Thrt->RChild=Thrt;
if (!T)
Thrt->LChild=Thrt;
else
{
Thrt->LChild=T;
pre=Thrt;
InThreading(T,pre);
pre->RFlag=Thread;
pre->RChild=Thrt;
Thrt->RChild=pre;
}
return true;
}
//中序创建线索二叉树
bool InOrderCreate(BiThrTree &T)
{
char data;
cin>>data;
if (data=='#')
{
T=NULL;
return false;
}
else
{
if (!(T=(BiThrTree)malloc(sizeof(BiThrTNode))))
{
return false;
}
T->data=data;
if(InOrderCreate(T->LChild))
T->LFlag=Link;
if(InOrderCreate(T->RChild))
T->RFlag=Link;
}
return true;
}
//遍历线索二叉树
bool InOrderTraverse_Thr(BiThrTree T)
{
BiThrTree p=T->LChild;
while(p!=T)
{
while(p->LFlag==Link)
p=p->LChild;
printf("%c\n",p->data);
while(p->RFlag==Thread&&p->RChild!=T)
{
p=p->RChild;
printf("%c\n",p->data);
}
p=p->RChild;
}
return true;
}
二叉树(3)——线索化
最新推荐文章于 2022-06-25 16:46:19 发布