版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/yg_hou/article/details/51107152
欢迎转载,转载请注明出处
中序线索树遍历
一.线索树
线索树是二叉树的一种改进,当二叉树的某个节点没有左(右)孩子时,将左(右)指针域指向遍历的上(下)一个位置。
so,节点由三个域增加到五个域,增加两个标志位,标识左(右)孩子指向的是左(右)子树,还是遍历的上(下)一个位置。
typedef int elementtype;
struct node{//节点的型
node* lchild;
node* rchild;
bool ltag;
bool rtag;
elementtype element;
};
typedef node* head;//指向树根root
typedef node* tree;//指向线索树的根节点
二.求节点的Next位置
如果某节点无右子树,则Next位置为遍历的下一个节点,如果有右子树,则Next位置为右子树的最左节点。
//中根遍历的下一个节点
node* inNext(node* p)
{
node* q=p->rchild;
if(p->rtag==true)//如果有右子树,找出右子树的最左节点
while(q->ltag==true)
q=q->lchild;
return q;
}
//中根遍历的上一个节点
node* inPre(node* p)
{
node *q= p->lchild;
if(p->ltag==true)//如果P的左子树存在,则其前驱结点为左子树的最右结点
while(q->rtag==true)
q=q->rchild;
return q;//左子树的最右结点
}
上面给出了求上一个节点的函数,这个函数在线索树插入算法(见我下一篇博客)中会用到。
三.线索树中序遍历
有了Next函数,中序遍历变得非常简单了。
void thInOrder(head h)//注意head不是树根,而是指向树根
{
node* temp;
temp=h;
do{
temp=inNext(temp);
if(temp!=h)
cout<<temp->element<<" ";
}while(temp!=h);
}
测试用例见下一篇博客《线索树插入左右孩子》。
今天就到这里啦~~~