根据一棵树的中序遍历与后序遍历构造二叉树。
注意:
你可以假设树中没有重复的元素。
例如,给出
中序遍历 inorder = [9,3,15,20,7]
后序遍历 postorder = [9,15,7,20,3]
返回如下的二叉树:
3
/ \
9 20
/ \
15 7
/**
* 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 i_start, int i_end,
vector<int>& postorder, int p_start, int p_end)
{
if(p_start > p_end){
return NULL;
}
int root_val = postorder[p_end];
int index = i_start;
for(int i = i_start; i<inorder.size();i++){
if(root_val == inorder[i]){
index = i;
break;
}
}
int left_size = index - i_start;
TreeNode* root = new TreeNode(root_val);
root->left = build(inorder, i_start, index - 1,
postorder, p_start, p_start + left_size - 1);
root->right = build(inorder, index + 1, i_end,
postorder, p_start + left_size, p_end - 1);
return root;
}
};