结构
/* 加入线索标识二叉链表表示法的结构模型 */
typedef struct BiTNode
{
TElemType data; /* 节点数据 */
struct BiTNode *lchild; /* 左孩子 */
struct BiTNode *rchild; /* 右孩子 */
int lTag; /* 左孩子-线索标识 */
int rTag; /* 右孩子-线索标识 */
} BiTNode;
以结点p为根的子树中序线索化
BiThrTree pre;
void InThreading(BiThrTree p)
{
if (p)
{
InThreading(p->lchild);
if (!p->lchild)
{
p->LTag=1;
p->lchild=pre;
}
else p->LTag=0;
if (!pre->rchild)
{
pre->RTag=1;
pre->rchild=p;
}
else pre->RTag=0;
pre=p;
InThreading(p->rchild);
}
}
带头结点的二叉树中序线索化
void InOrderThreading(BiThrTree &Thrt,BiThrTree T)
{
Thrt=new BiThrNode;
Thrt->LTag=0;
Thrt->RTag=1;
Thrt->rchild=Thrt;
if(!T) Thrt->lchild=Thrt;
else
{
Thrt->lchild=T;
pre=Thrt;
InThreading(T);
pre->rchild=Thrt;
pre->RTag=1;
Thrt->rchild=pre;
}
}
此中序遍历从H开始,序列为HDIBJEAFCG,通过I可以直接得到I的前驱为D,后继为B。而不需要再次遍历找到。
中序遍历线索二叉树
void InOrderTraverse_Thr(BiThrTree T)
{
BiThrTree p;
p=T->lchild;
while (p!=T)
{
while (p->LTag==0) p=p->lchild;
cout<<p->data;
while (p->RTag==1&&p->rchild!=T)
{
p=p->rchild;
cout<<p->data;
}
p=p->rchild;
}
}
如图为带有头结点的双向二叉链表,灰色箭头为前驱,黑色箭头为后继。