Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
题目解析:
跟上题一样,利用遍历的特性,从后向前找。
class Solution{
public:
TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
if(inorder.size() != postorder.size())
return NULL;
return generateSub(inorder,0,inorder.size()-1,postorder,0,postorder.size()-1);
}
TreeNode *generateSub(vector<int> &inorder,int begin1,int end1, vector<int> &postorder,int begin2,int end2){
if(begin1>end1 || begin2>end2)
return NULL;
int i;
for(i = end1;i >= begin1;i--){
if(inorder[i] == postorder[end2])
break;
}
TreeNode *p = new TreeNode(postorder[end2]);
p->right = generateSub(inorder,i+1,end1,postorder,end2-end1+i,end2-1);
p->left = generateSub(inorder,begin1,i-1,postorder,begin2,end2-end1+i-1);
return p;
}
};