1. 程式人生 > 實用技巧 >HDU-1710-二叉樹

HDU-1710-二叉樹

 1 #include <iostream>
 2 using namespace std;
 3 
 4 typedef long long ll;
 5 
 6 const int maxn = 1010;
 7 
 8 // 輸入先序遍歷和中序遍歷, 求後序遍歷;
 9 
10 int pre[maxn], in[maxn], post[maxn];
11 int k;
12 
13 struct node
14 {
15     int value;
16     node *l, *r;
17     node(int value = 0, node *l = nullptr, node *r = nullptr):
18 value(value), l(l), r(r){} 19 }; 20 21 void buildtree_dfs(int l, int r, int &t, node* &root) 22 { 23 int flag = -1; 24 for(int i = l; i <= r; i++) 25 { 26 if(in[i] == pre[t]) 27 { 28 flag = i; 29 break; 30 } 31 } 32
if(flag == -1) return; 33 root = new node(in[flag]); 34 t++; 35 if(flag > l) buildtree_dfs(l, flag - 1, t, root->l); 36 if(flag < r) buildtree_dfs(flag + 1, r, t, root->r); 37 } 38 39 void preorder(node *root) 40 { 41 if(root != nullptr) 42 { 43 post[k++] = root->value;
44 preorder(root->l); 45 preorder(root->r); 46 } 47 } 48 49 void inorder(node *root) 50 { 51 if(root != nullptr) 52 { 53 inorder(root->l); 54 post[k++] = root->value; 55 inorder(root->r); 56 } 57 } 58 59 void postorder(node *root) 60 { 61 if(root != nullptr) 62 { 63 postorder(root->l); 64 postorder(root->r); 65 post[k++] = root->value; 66 } 67 } 68 69 int main() 70 { 71 int n; 72 while(cin >> n) 73 { 74 for(int i = 1; i <= n; i++) cin >> pre[i]; 75 for(int i = 1; i <= n; i++) cin >> in[i]; 76 node *root; 77 int t = 1; 78 buildtree_dfs(1, n, t, root); 79 k = 0; 80 postorder(root); 81 for(int i = 0; i < k; i++) 82 { 83 cout << post[i]; 84 if(i != k - 1) cout << " "; 85 } 86 cout << endl; 87 } 88 return 0; 89 }