Tree Traversals

来源:互联网 发布:nba勇士火箭数据 编辑:程序博客网 时间:2024/05/20 18:44

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

Solution:

#include<iostream>#include<vector>#include<queue>#include<fstream>using namespace std;struct Node{int num;Node* left;Node* right;};Node* get_tree(vector<int>& post_seq,vector<int>& in_seq,int b1,int e1,int b2,int e2){if(b1 > e1 || b2 > e2)return NULL;else{Node* n = new Node();n->num = post_seq[e1];int index;for(int i = b2;i <= e2; ++ i){if(n->num == in_seq[i]){index = i;break;}}n->left = get_tree(post_seq,in_seq,b1,b1 + index - b2 - 1,b2,index - 1);n->right = get_tree(post_seq,in_seq,b1 + index - b2,e1 - 1,index + 1,e2);return n;}}void level_travel(Node* r,vector<int>& lev_seq){queue<Node*> tmp;tmp.push(r);while(!tmp.empty()){Node* n = tmp.front();lev_seq.push_back(n->num);if(n->left != NULL)tmp.push(n->left);if(n->right != NULL)tmp.push(n->right);delete n;tmp.pop();}}int main(){int n;cin >> n;vector<int> post_seq,in_seq,lev_seq;for(int i = 0;i < n;++ i){int t;cin >> t;post_seq.push_back(t);}for(int i = 0;i < n;++ i){int t;cin >> t;in_seq.push_back(t);}Node* root = get_tree(post_seq,in_seq,0,post_seq.size() - 1,0,in_seq.size() - 1);level_travel(root,lev_seq);vector<int>::iterator it;for(it = lev_seq.begin();it != lev_seq.end();++ it){cout << *it;if(it != (lev_seq.end() - 1))cout << " ";}}



原创粉丝点击