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