题目描述:
输入某二叉树的前序遍历和中序遍历的结果,请构建该二叉树并返回其根节点。 假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7] Output: [3,9,20,null,null,15,7]
上题解:
class Solution {
public:
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
if(preorder.size()==0 || inorder.size()==0){
return NULL;
}
int index=0;
for( ; index<inorder.size(); index++){
if(inorder[index]==preorder[0]){
break;
}
}
TreeNode *root=new TreeNode(inorder[index]);
vector<int>preorder_right, preorder_left;
vector<int>inorder_right, inorder_left;
for(int j=0; j<index; j++){
preorder_left.push_back(preorder[j+1]);
inorder_left.push_back(inorder[j]);
}
for(int k=index+1; k<inorder.size(); k++){
preorder_right.push_back(preorder[k]);
inorder_right.push_back(inorder[k]);
}
root->left=buildTree(preorder_left, inorder_left);
root->right=buildTree(preorder_right, inorder_right);
return root;
}
};
|