题目链接:http://pat.zju.edu.cn/contests/pat-a-practise/1020
题目较简单,根据后序和中序遍历写出二叉树的层序遍历,我的思想:根据2个序列递归构建二叉树,再层序遍历。
只要计算好下标就好了。
1 #include<iostream> 2 #include<vector> 3 #include<queue> 4 using namespace std; 5 6 struct Node 7 { 8 int val; 9 Node* left; 10 Node* right; 11 }; 12 13 /*递归建树*/ 14 Node* buildtree(vector<int> post, int i, int j, vector<int> in, int k, int h) 15 { 16 if(i > j || k > h) 17 return NULL; 18 Node* n = new Node; 19 n->val = post[j]; 20 int mid(-1); 21 for(int i=k; i<=h; ++i) 22 if(in[i] == post[j]) 23 { 24 mid = i; 25 break; 26 } 27 n->left = buildtree(post, i, i+mid-k-1, in, k, mid-1); 28 n->right = buildtree(post, i+mid-k, j-1, in, mid+1, h); 29 return n; 30 } 31 32 int main() 33 { 34 int n; 35 while(cin>>n) 36 { 37 vector<int> post(n, 0); 38 vector<int> in(n, 0); 39 for(int i=0; i<n; ++i) 40 cin>>post[i]; 41 for(int i=0; i<n; ++i) 42 cin>>in[i]; 43 Node *root = buildtree(post, 0, n-1, in, 0, n-1); 44 queue<Node*> q; 45 q.push(root); 46 int m(0); 47 while(!q.empty()) 48 { 49 if(q.front()->left != NULL) 50 q.push(q.front()->left); 51 if(q.front()->right != NULL) 52 q.push(q.front()->right); 53 if(m == n-1) 54 cout<<q.front()->val<<endl; 55 else 56 cout<<q.front()->val<<" "; 57 q.pop(); 58 ++m; 59 } 60 } 61 return 0; 62 }