思路
/**
* 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* buildTree(vector<int>& inorder, vector<int>& postorder) {
return build(inorder,0,inorder.size()-1,postorder,0,postorder.size()-1);
}
TreeNode* build(vector<int>& inorder,int s0,int e0,vector<int>& postorder,int s1,int e1){
if(s0 > e0 || s1 > e1) return NULL;
int rootval = postorder[e1];
TreeNode *root = new TreeNode(rootval);
int mid = 0;
for(int i = s0; i <= e0; i++){
if(inorder[i] == rootval) mid = i;
}
root->left = build(inorder,s0,mid-1,postorder,s1,s1+mid-s0-1);
root->right = build(inorder,mid+1,e0,postorder,s1+mid-s0,e1-1);
return root;
}
};