【PAT】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
分析:考察树的建立和遍历。
课参考《编程之美》3.9
#include<iostream> #include<map> #include<vector> #include<queue> using namespace std; struct Node{ Node *left; Node *right; int value; Node():left(NULL),right(NULL){} }; void Rebuild(int * PostOrder, int * InOrder, int len, Node* &root){ //判断何时结束递归 if(PostOrder == NULL || InOrder == NULL) { root = NULL; return ; } if(root == NULL) root = new Node; root->value = *(PostOrder + len - 1); root->left = NULL; root->right = NULL; if(len == 1) return; int count = 0; int *temp = InOrder; while(*temp != *(PostOrder + len -1)) { count ++; temp++; if(count > len) break; } int left = temp - InOrder ; int right = len - left - 1; if(left > 0) Rebuild(PostOrder, InOrder, left, root->left); if(right > 0) Rebuild(PostOrder + left, InOrder+left+1, right, root->right); } int main() { int n,i,t; while(cin>>n) { int *PostOrder = new int[n]; int *InOrder = new int[n]; for(i=0; i<n; i++) cin>>PostOrder[i]; for(i=0; i<n; i++) cin>>InOrder[i]; Node *root = new Node; int post_start,in_start; post_start = 0; in_start = 0; Rebuild(PostOrder, InOrder, n, root); queue<Node *> q; q.push(root); int flag = 1; while(!q.empty()){ if(q.front()->left != NULL) q.push(q.front()->left); if(q.front()->right != NULL) q.push(q.front()->right); if(flag != n) cout<<q.front()->value<<" "; else cout<<q.front()->value; flag ++; q.pop(); } cout<<endl; } return 0; }