1020 Tree Traversals (25)(25 分)
题目描述:
Suppose that all the keys in a binary tree are distinct positive integers. Given the postorder and inorder traversal sequences, you are supposed to output the level order traversal sequence of the corresponding binary tree.
输入格式:
Each input file contains one test case. For each case, the first line gives a positive integer N (<=30), the total number of nodes in the binary tree. The second line gives the postorder sequence and the third line gives the inorder sequence. All the numbers in a line are separated by a space.输出格式:
For each test case, print in one line the level order traversal sequence of the corresponding binary tree. All the numbers in a line must be separated by exactly one space, and there must be no extra space at the end of the line.
题目大意:
根据后续遍历和先序遍历来输出层序遍历的结果。
解题方法:
由完全二叉树的性质(当然我不是说这题是完全二叉树),我们可以知道
左孩子编号=父亲结点编号*2+1
右孩子编号=父亲结点编号*2+2
(PS:根结点编号从0开始)
那么,我们就可以通过求先序遍历的方法,用一个数组level保存遍历结果,其中的每个元素的下标由父节点决定。
void transTolevel(int root, int start, int end, int idx)说明:
root:子树根结点在后续遍历中的位置
start:子树遍历起点在后续遍历中的位置
end:子树遍历终点在后续遍历中的位置
idx:对应父亲结点下标
易错点:
1. 在递归调用transTolevel过程中,对左子树的调用时,第一个参数root不能写成i-1。
2.map和level数组要开的大一点,避免左右结点都在左边时越界或者题目编号不按套路出牌(比较大)
程序:
#include <stdio.h>
#include <algorithm>
using namespace std;
int post[31], level[10000], map[10000];
void transTolevel(int root, int start, int end, int idx)
{
if (start > end)
return; /* 如果起点超过终点则结束 */
int i = map[post[root]]; /* 根结点在中序遍历中的位置 */
level[idx] = post[root];
transTolevel(root - (end - i + 1), start, i - 1, idx * 2 + 1);
transTolevel(root - 1, i + 1, end, idx * 2 + 2);
}
int main(int argc, char const *argv[])
{
int N, x, cnt = 1;
scanf("%d", &N);
fill(level, level+10000, -1); /* 初始化层序遍历 */
for (int i = 0; i < N; i++) /* 输入后续遍历结果 */
scanf("%d", &post[i]);
for (int i = 0; i < N; i++) /* 输入中序遍历结果 */
{
scanf("%d", &x);
map[x] = i; /* 建立下标与值的映射 */
}
transTolevel(N-1, 0, N-1, 0);
printf("%d", level[0]);
for (int i = 1; i < 10000; i++)
{
if (level[i] != -1)
{
printf(" %d", level[i]);
cnt++; /* 计算输出的个数 */
}
if (cnt == N) /* 当输出N个数后停止循环 */
break;
}
return 0;
}
如果对您有帮助,帮忙点个小拇指呗~