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 7Sample 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 << " ";}}
- Tree Traversals
- Tree Traversals
- Tree Traversals
- HDOJ1710 Binary Tree Traversals
- traversals for Binary Tree
- HDOJ1710 Binary Tree Traversals
- hdoj1710Binary Tree Traversals
- 1020. Tree Traversals
- pat 1020 Tree Traversals
- 1020. Tree Traversals (25)
- 1020. Tree Traversals
- HDU1710:Binary Tree Traversals
- Hdu Binary Tree Traversals
- PAT_1020: Tree Traversals
- PAT 1020 Tree Traversals
- 【PAT】1020. Tree Traversals
- 1020. Tree Traversals (25)
- hdu Binary Tree Traversals
- 查看和修改mysql编码
- ReportViewer 自定义报表应用
- getopt()函数的使用
- mobile web app 介绍
- webservice查询天气预报
- Tree Traversals
- Ubuntu下NS3安装步骤
- 计算几何 ural 1754. Explosion in a Pyramid
- 警世之言
- WinCE中触摸屏驱动开发详解(2440)
- Java基础之abstract class与interface,Override与Overload
- OpenCV深入学习(2)-Mat构造初始化等
- <转载>条件变量(互斥量)与pthread_cond_wait函数详解
- 合并烧写程序BIN文件的两种方法