PAT甲级练习1020. Tree Traversals (25)

来源:互联网 发布:finalcut mac 编辑:程序博客网 时间:2024/06/12 23:02

1020. Tree Traversals (25)

时间限制
400 ms
内存限制
65536 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
这是道二叉树遍历的题,首先几种二叉树的遍历方式:

postorder 后序遍历:左 右 中

inorder 中序遍历:左 中 右

preorder 前序遍历: 中 左 右

level order 层次遍历:按每层结构

分析了下数据格式,因为根节点总是在postorder的最后,得到根节点后在inorder中可以得到其左右子集,然后再分别在子集中找到子根节点,递归地得到每一层的节点

#include <iostream>#include <cmath>#include <algorithm>#include <vector>using namespace std;int n;vector<vector<int>> level(31);vector<int> postorder(31);vector<int> inorder(31);vector<int> levelorder(31);int indexof(int x, vector<int> y){for(int i=0; i<y.size(); i++){if(x==y[i]) return i;}}int closest(vector<int> x, vector<int> y, int root){for(int i=indexof(root, y); i>=0; i--){for(int j=0; j<x.size(); j++){if(y[i]==x[j]) return j;}}}void classify(int root, vector<int> left, vector<int> right, int l){level[l].push_back(root);if(!left.empty()){int subrootindex = closest(left, postorder, root);int subroot = left[subrootindex];vector<int> subleft(left.begin(), left.begin()+subrootindex);vector<int> subright(left.begin()+subrootindex+1, left.end());classify(subroot, subleft, subright, l+1);}if(!right.empty()){int subrootindex = closest(right, postorder, root);int subroot = right[subrootindex];vector<int> subleft(right.begin(), right.begin()+subrootindex);vector<int> subright(right.begin()+subrootindex+1, right.end());classify(subroot, subleft, subright, l+1);}}int main(){scanf("%d", &n);for(int i=1; i<=n; i++){scanf("%d", &postorder[i]);}for(int i=1; i<=n; i++){scanf("%d", &inorder[i]);}int root = postorder[n];int index = indexof(root, inorder);vector<int> left(inorder.begin()+1, inorder.begin()+index);vector<int> right(inorder.begin()+index+1, inorder.begin()+n+1);classify(root, left, right, 1);printf("%d", root);int k=2;while(!level[k].empty()){for(int i=0; i<level[k].size(); i++){printf(" %d", level[k][i]);}k++;}cin>>n;return 0;}

注意下vector初始化从另一个vector复制值时前后界限的问题:前一个就是开始的位置,后一个指向结束的下一个位置!


0 0
原创粉丝点击