本题要求实现对于给定的二叉树,打印后序序列中指定序号的结点。
函数接口定义:
void PrintNode(BiTree T);
T是二叉树树根指针,PrintNode函数输出给定二叉树的后序序列中第n个结点,n为结点在后序序列中的序号,从1开始编号。
其中BinTree结构定义如下:
typedef char ElemType;
typedef struct BiTNode
{
ElemType data;
struct BiTNode *lchild, *rchild;
}BiTNode, *BiTree;
裁判测试程序样例:
#include
#include
typedef char ElemType;
typedef struct BiTNode
{
ElemType data;
struct BiTNode *lchild, *rchild;
}BiTNode, *BiTree;
BiTree Create();
void PrintNode(BiTree T);
int n;//要打印的结点的在先序序列中的序号
int main()
{
BiTree T = Create();
scanf("%d", &n);
printf("The %d-th node in postorder is: ", n);
PrintNode(T);
printf("n");
return 0;
}
输出样例(对于图中给出的树,当输入的n为2时):
The 2-th node in postorder is: B
这个题多少还是有点问题的,题目没有说清楚到底应该输出哪个结点的值,按照通过的代码的意思,应该是输出的根节点左子树的数值,没有具体的搞清楚!!
答案如下:
void PrintNode(BiTree T){
BiTNode *t = T;
if(T==NULL)
return;
else{
PrintNode(t->lchild);
PrintNode(t->rchild);
n--;
if(n == 0){
printf("%d",t->data);
}
}
}
就是每次进入这个循环,n就--,直到n为零,也就是后续遍历时我们找到的第n个结点。这样看就是找后续遍历过程中我们找到的第n个节点



