1020 Tree Traversals (25分)

Posted 绀香零八

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了1020 Tree Traversals (25分)相关的知识,希望对你有一定的参考价值。

1020 Tree Traversals (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.

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

代码如下:
中文版题目如下👇
L2-006 树的遍历 (25分)

#include<bits/stdc++.h>
using namespace std;
vector<int> post,in;
map<int,int> ans;
void level(int root,int start,int end,int index)
	if(start>end) return;
	int k;
	for(k=start;k<end;k++) if(in[k]==post[root]) break;
	ans[index] = post[root];
	level(root-1-end+k,start,k-1,2*index+1);
	level(root-1,k+1,end,2*index+2);

int main()
	ios::sync_with_stdio(false);
	cin.tie(0),cout.tie(0);
	int N,flag=0;
	cin >> N;
	post.resize(N);
	in.resize(N);
	for(int i=0;i<N;i++) cin >> post[i];
	for(int i=0;i<N;i++) cin >> in[i];
	level(N-1,0,N-1,0);
	for(int i=0;i<ans.size();i++)
		if(ans[i])
			if(!flag) flag = 1;
			else cout << " ";
			cout << ans[i];
			
	
	return 0;
 

以上是关于1020 Tree Traversals (25分)的主要内容,如果未能解决你的问题,请参考以下文章

1020 Tree Traversals (25 分)

1020 Tree Traversals (25分)

1020 Tree Traversals (25 分)

PAT Advanced 1020 Tree Traversals (25分)

1020 Tree Traversals (25 分) 难度: 中 / 知识点: 哈希表建树 遍历树

PAT 1020 Tree Traversals