根据一棵树的前序遍历与中序遍历构造二叉树。
注意:
你可以假设树中没有重复的元素。
例如,给出
前序遍历 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() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
if(preorder.empty() || inorder.empty()) return NULL;
TreeNode* root=new TreeNode(preorder[0]);
int index=0;
for(;index<inorder.size();index++){
if(inorder[index]==preorder[0]){
break;
}
}
vector<int> preorder_left, preorder_right;
vector<int> inorder_left, inorder_right;
for(int i=0;i<index;i++){
preorder_left.push_back(preorder[i+1]);
inorder_left.push_back(inorder[i]);
}
for(int i=index+1;i<preorder.size();i++){
preorder_right.push_back(preorder[i]);
inorder_right.push_back(inorder[i]);
}
TreeNode* L=buildTree(preorder_left,inorder_left);
TreeNode* R=buildTree(preorder_right,inorder_right);
root->left=L;
root->right=R;
return root;
}
};