1020. Tree Traversals (25)

来源:互联网 发布:origin图中点显示数据 编辑:程序博客网 时间:2024/05/17 02:42

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.

Input Specification:

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.

Output Specification:

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.

Sample Input:
7
2 3 1 5 7 6 4
1 2 3 4 5 6 7
Sample Output:
4 1 6 3 5 7 2

题目意思:根据后序和中序输出层序。
后序的最后一个根结点总是根结点。pos为中序中找到该根结点的位置,则中序划分为左子树和右子树。
左子树在后序中根结点的位置为(root - (right - pos + 1))。root为后序中根结点位置,end - pos + 1为右子树个数,
左子树在中序中的起始点为start, 末尾点为pos - 1
右子树的在后序(左右根)中的根节点为当前根结点前一个节点root - 1.
右子树起始点为pos + 1. 末尾点为 end。
输出层序的结果可以用level数组保存。题目给的测试用例都能通过,如果30个节点全是右子树的例子,不能用level数组了。参考http://www.liuchuo.net/archives/2100

include
include
include
using namespace std;
const int maxn = 35;
int n;
int postorder[maxn], inorder[maxn], level[100000];
void dfs(int root, int left, int right, int idx)
{
if(left > right)
return ;
int pos;
for(pos = left; pos < right; pos++){
if(inorder[pos] == postorder[root])
break;
}
level[idx] = postorder[root];
dfs(root - 1 - right + pos, left, pos - 1, 2 * idx + 1);
dfs(root - 1, pos + 1, right, 2 * idx + 2);
}
int main()
{
scanf(“%d”, &n);
memset(level, -1, sizeof(level));
for(int i = 0; i < n; i++)
scanf(“%d”, postorder + i);
for(int i = 0; i < n; i++)
scanf(“%d”, inorder + i);
dfs(n - 1, 0, n - 1, 0);
int cnt = 0;
for(int i = 0; i < 100000; i++){
if(level[i] != -1){
printf(“%d”, level[i]);
cnt++;
if(cnt != n)
printf(” “);
else break;
}
}
return 0;
}

0 0