【正确答案】根据中序线索二叉树的定义得到求第一个结点(first())、下一个结点(next())、最后一个结点(last())和前一个结点(prior())的函数,再设计中序正向遍历二叉树(forward())和中序反向遍历二叉树(back())的函数。
实现本题功能的程序代码如下:
BTNode *first(BTNode *root)
//返回root为根的中序线索树中的第一个结点
{
while(root→ltag==0)
root=root→left;
return root;
}
BTNode *last(BTNode *root)
//返回root为根的中序线索树中的最后一个结点
{
BTNode *p=root→right;
return pi
}
BTNode *next(BTNode *root,BTNode *q) //返回q结点的后继结点
{
BTNode *p=q→right,*n;
if(q→rtag==0) //有右孩子时
while(p→ltag==0)
p=p→left;
n=p;
if(n==root)
//若q为最后一个结点,则返回NULL,否则返回n
return NULL;
else
return n;
}
BTNode *prior(BTNode *root,BTNode *q) //返回q的前驱结点
{
BTNode *p=q→left,*n;
if(q→ltag==0)
while(p→rtag==0)
p=p→right;
n=p;
if(n==root) //若q为第一个结点,则返回NULL,否则返回n
return NULL;
else
return n;
}
void forward(BTNode *root) //中序正向遍历二叉树
{
BTNode *p;
for(p=first(root);p!=NULL;p=next(root,p))
visit(p); //访问p,visit是已经定义的访问函数
}
void back(BTNode *root) //中序反向遍历二叉树
{
BTNode *p;
p=last(root);
for(p=last(root);p!=NULL;p=prior(root,p))
visit(p); //访问p,visit是已经定义的访问函数
}
【答案解析】