线索二叉树
Lchild | LTag | data | RTag | Rchild |
代码做一个线索二叉树的结构体
typedef struct tyust
{
type Ltag,Rtag;
struct tyust *Lchild,*Rchild;
char data;
}*bit_tree;
通过线序遍历建立一个二叉树//注:一般使用先序遍历建立树,方便使用递归建立
void creat_bittree(bit_tree &T)
{
char c;
scanf("%c",&c);
T=(bit_tree)malloc(sizeof(tyust));//为参数分配空间地址
if(' '==c)//如果输入是空格
{
T=NULL;
}
else
{
T->data=c;
creat_bittree(T->Lchild);//遍历左子树
creat_bittree(T->Rchild);//遍历右子树
}
}
中序遍历线索化二叉树
void thread_link(bit_tree p)
{
if(p)
{
thread_link(p->Lchild);//左子树线索化
if(!p->Lchild)
{
p->Ltag=thread;//前驱
p->Lchild=pre;
}
if(!pre->Rchild)
{
pre->Rtag=thread;//后继
pre->Rchild=p;
}
pre=p;//更换前驱
thread_link(p->Rchild);
}
}
建立一个头节点,完善头节点指向:
void head_build(bit_tree &head,bit_tree T)//建立头节点,传入树的root
{
head=(bit_tree)malloc(sizeof(tyust));
head->Ltag=link;
head->Rchild=head;
head->Rtag=thread;//头节点初始化
if(!T)//空的二叉树
{
head->Lchild=head;//指向自己
}else
{
head->Lchild=T;
pre=head;//pre是前驱
thread_link(T);//调用线索化
pre->Rchild=head;
pre->Rtag=thread;
head->Rchild=pre;//首尾相连
}
}
中序遍历节点显示:
void center_display(bit_tree head)
{
bit_tree temp=(bit_tree)malloc(sizeof(tyust));
temp=head->Lchild;//得到树根
while(temp!=head)//没有循环完
{
while(temp->Ltag==link)//如果有左孩子,就一直找到叶子为止
{
temp=temp->Lchild;
}
cout<<temp->data<<" ";//打印出来
//如果节点右孩子表示后继且不是中序遍历的最后一个节点
while(temp->Rtag==thread&&temp->Rchild!=head)
{
temp=temp->Rchild;
cout<<temp->data<<" ";//打印出来
}
temp=temp->Rchild;
}
}