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;
}
如果對您有幫助,幫忙點個小拇指唄~