1020. Tree Traversals (25) PAT+tree

来源:互联网 发布:vb和易语言 编辑:程序博客网 时间:2024/05/21 13:55

说明:告诉后序和中序遍历,求层序。使用队列完成。

1020. Tree Traversals (25)

时间限制
400 ms
内存限制
32000 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue

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:
72 3 1 5 7 6 41 2 3 4 5 6 7
Sample Output:
4 1 6 3 5 7 2
C++代码:
#include<iostream>#include<vector>#include<queue>using namespace std;vector<int> a, b, c;int N;queue<vector<int>> q;vector<int> t;void find(){t.push_back(a[N-1]);q.push(t);while(!q.empty()){vector<int> pop_one;pop_one = q.front();//寻找pop_one中元素在后序(a)中的最大下标vector<int> sub;for(int i=0; i<pop_one.size(); i++){for(int j=0; j<N; j++){if(a[j] == pop_one[i]){sub.push_back(j);break;}}}int max_sub = 0;for(int i=1; i<sub.size(); i++){if(sub[i] > sub[max_sub]){max_sub = i;}}c.push_back(a[sub[max_sub]]);int tt = a[sub[max_sub]];int flag_i;for(int i=0; i<N; i++){if (b[i] == tt){b[i] = 0;flag_i = i;break;}}vector<int> t1, t2;//vector<int> t_temp;int sub_i = 0; int sub_j = N-1;int f1 = 0, f2 = 0;for(int i=(flag_i-1); i>=0; i--){if (b[i] == 0){sub_i = i;f1 = 1;break;}}if(f1==1){sub_i++;}for(int k = sub_i; k<flag_i; k++){t1.push_back(b[k]);}for(int i = (flag_i+1); i<N; i++){if(b[i] == 0){sub_j = i;f2 = 1;break;}}if(f2==1){sub_j--;}for(int k = (flag_i+1); k<=sub_j; k++){t2.push_back(b[k]);}if (t1.size()){q.push(t1);}if(t2.size()){q.push(t2);}q.pop();}}int main(){cin>>N;int temp;for(int i=0; i<N; i++){cin>>temp;a.push_back(temp);}for(int i=0; i<N; i++){cin>>temp;b.push_back(temp);}find();for(int i=0; i<c.size(); i++){if(i<(c.size()-1)){cout<<c[i]<<" ";}else{cout<<c[i]<<endl;}}system("pause");return 0;}


0 0
原创粉丝点击