For this problem just need to know the structure of two traversal.

1. It is hard to find the root node in the inorder traversal but it is easy in postorder. The last one in post order is the root. 

2. At same time, you can not figure out what is the boundary for left branch and right branch in post order. But you can do it in inorder.

 1 /**
 2  * Definition for binary tree
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     TreeNode *getTree(vector<int> &iv, vector<int> &pv, int ist, int ied, int pst, int ped) {
13         if (ist > ied) return NULL;
14         int current = -1, len = 0;
15         for (int i = ist; i <= ied; i++) {
16             if (pv[ped] == iv[i]) {
17                 current = i;
18                 break;
19             }
20         }
21         len = current - ist;
22         TreeNode *root = new TreeNode(pv[ped]);
23         root->left = getTree(iv, pv, ist, current-1, pst, pst+len-1);
24         root->right = getTree(iv, pv, current+1, ied, pst+len, ped-1);
25     }
26     TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
27         if (inorder.size() == 0 || inorder.size() != postorder.size()) return NULL;
28         return getTree(inorder, postorder, 0, inorder.size()-1, 0, postorder.size()-1);
29     }
30 };

 

posted on 2015-03-19 05:27  keepshuatishuati  阅读(131)  评论(0编辑  收藏  举报