对于给定的二叉树,本题要求你按从上到下顺序输出指定结点的所有祖先结点。
输入格式:
首先第一行给出一个正整数 N(≤10),为树中结点总数。树中的结点从 0 到 N−1 编号。
随后 N 行,每行给出一个对应结点左右孩子的编号。如果某个孩子不存在,则在对应位置给出 "-"。编号间以 1 个空格分隔。
最后一行给出一个结点的编号i(0≤i≤N-1)。
输出格式:
在一行中按规定顺序输出i的所有祖先结点的编号。编号间以 1 个空格分隔,行首尾不得有多余空格。
输入样例:
7
2 -
- 6
- -
0 5
- -
4 1
- -
4
输出样例:
3 5
代码长度限制
16 KB
时间限制
400 ms
内存限制
64 MB
#include<stdio.h>
#include<stdlib.h>
typedef struct TNode
{
int Left;
int Right;
int Parent;
}Tree;
Tree tree[12];
void CreateTree(int n){
for (int i = 0; i < n; i++)
{
tree[i].Parent = -1;
}
for (int i = 0; i < n; i++)
{
char left, right;
getchar();
scanf("%c %c",&left,&right);
if (left == '-')
{
tree[i].Left = -1;
}
else
{
tree[i].Left = left- '0';
tree[left - '0'].Parent = i;
}
if (right == '-')
{
tree[i].Right = -1;
}
else
{
tree[i].Right = right - '0';
tree[right - '0'].Parent = i;
}
}
}
void Visit()
{
int ans[12];
int n = 0;
int i;
int child;
scanf("%d",&child);
while (tree[child].Parent != -1)
{
ans[n++] = tree[child].Parent;
child = tree[child].Parent;
}
for (i = n - 1; i >= 0; i--)
{
if (i == n - 1)
{
printf("%d",ans[i]);
}
else
{
printf(" %d",ans[i]);
}
}
}
int main()
{
int n;
scanf("%d",&n);
CreateTree(n);
if (n > 1)
{
Visit();
}
return 0;
}