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 7Sample Output:
4 1 6 3 5 7 2
- #include <iostream>
- #include <string>
- #include <algorithm>
- #include <memory.h>
- #include <cstdio>
- #include <cstdlib>
- #include <queue>
- #include <vector>
- using namespace std;
- #define MAX 0Xfffffff
- struct Node{
- Node* left, *right;
- int num;
- };
- int k;
- Node* getTree(vector<int> post, int ps, int pe, vector<int> in, int is, int ie){
- if(ps>pe || is>ie){
- return NULL;
- }else{
- Node *node = new Node();
- int num = post[pe];
- node->num = num;
- int index;
- for(int i=0;i<in.size();++i){
- if(in[i] == num){
- index = i;
- }
- }
- node->left = getTree(post, ps, ps+index-1-is, in, is, index-1);
- node->right = getTree(post, ps+index-is, pe-1, in, index+1, ie);
- return node;
- }
- }
- void print(Node * root){
- queue<Node*> q;
- q.push(root);
- bool first = true;
- while(!q.empty()){
- Node * node = q.front();
- q.pop();
- if(first){
- first = false;
- }else{
- printf(" ");
- }
- printf("%d", node->num);
- if(node->left!=NULL)
- q.push(node->left);
- if(node->right!=NULL)
- q.push(node->right);
- delete node;
- }
- }
- int main(){
- //freopen("in.txt", "r", stdin);
- vector<int> post, in;
- int n;
- int t;
- cin>>n;
- for(int i=0;i<n;++i){
- scanf("%d", &t);
- post.push_back(t);
- }
- for(int i=0;i<n;++i){
- scanf("%d", &t);
- in.push_back(t);
- }
- print(getTree(post, 0, post.size()-1, in, 0, in.size()-1));
- printf("\n");
- //fclose(stdin);
- }