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 a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* helper(vector<int> &inorder, int begin1, int end1, vector<int> &postorder, int begin2, int end2)
{
if (begin2 > end2)
return NULL;
int lenleft = find(inorder.begin(),inorder.end(),postorder[end2])-inorder.begin()-begin1;
TreeNode *p = new TreeNode(postorder[end2]);
p->left = helper(inorder,begin1,begin1+lenleft-1,postorder,begin2,begin2+lenleft-1);
p->right = helper(inorder,begin1+lenleft+1,end1,postorder,begin2+lenleft,end2-1);
return p;
}
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder)
{
return helper(inorder, 0, inorder.size()-1, postorder, 0, postorder.size()-1);
}
};