Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
For example, given
inorder = [9,3,15,20,7]
postorder = [9,15,7,20,3]
Return the following binary tree:
3
/ \
9 20
/ \
15 7
1 class Solution { 2 public: 3 TreeNode*buildchild(vector<int>& postorder, vector<int>& inorder,int p1,int p2, int i1, int i2) { 4 if (i2 < i1) 5 return NULL; 6 int nowroot = postorder[p2]; 7 TreeNode*ans = new TreeNode(nowroot); 8 for (int i = i1; i <= i2; i++) 9 if (inorder[i] == nowroot) { 10 int left = i - i1, right = i2 - i; 11 if (i != i1) 12 ans->left = buildchild(postorder, inorder,p1,p1+left-1, i1, i - 1); 13 if (i != i2) 14 ans->right = buildchild(postorder, inorder, p1 + left, p2 - 1, i + 1, i2); 15 } 16 return ans; 17 } 18 TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) { 19 return buildchild(postorder, inorder, 0,postorder.size()-1,0, inorder.size() - 1); 20 } 21 };