Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.

/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode* Build(vector<int>& inorder,vector<int>& postorder,int s1,int e1,int s2,int e2){ if(s1>e1||s2>e2)return NULL; TreeNode* ret=new TreeNode(postorder[e2]); int i=s1; while(i<=e1){ if(inorder[i]==postorder[e2])break; i++; } ret->left=Build(inorder,postorder,s1,i-1,s2,s2+i-s1-1); ret->right=Build(inorder,postorder,i+1,e1,s2+i-s1,e2-1); } TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) { // Note: The Solution object is instantiated only once and is reused by each test case. return Build(inorder,postorder,0,inorder.size()-1,0,inorder.size()-1); } };