输入某二叉树的前序遍历和中序遍历的结果,请重建该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
例如,给出
前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]
返回如下的二叉树:
3
/ \
9 20
/ \
15 7
限制:
0 <= 节点个数 <= 5000
注意:本题与主站 105 题重复:https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/
题目链接:https://leetcode-cn.com/problems/zhong-jian-er-cha-shu-lcof/
思路
递归。
主要难度在于找左右子树分界线时的index容易算错。
/**
* 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) {
if(preorder.size()==0 || preorder.size()!=inorder.size()){
return nullptr;
}
return getChild(preorder, inorder, 0, preorder.size()-1, 0, inorder.size()-1);
}
TreeNode* getChild(vector<int>& preorder, vector<int>& inorder, int pl, int pr, int il, int ir){
if(pl>pr || il>ir){
return nullptr;
}
TreeNode* root = new TreeNode(preorder[pl]);
if(pl==pr){
return root;
}
int iroot = 0;
while(inorder[il+iroot]!=preorder[pl]){
++iroot;
}
auto lchild = iroot==0? nullptr: getChild(preorder, inorder, pl+1, pl+iroot, il, il+iroot-1);
auto rchild = il+iroot==ir? nullptr: getChild(preorder, inorder, pl+iroot+1, pr, il+iroot+1, ir);
root->left = lchild;
root->right = rchild;
return root;
}
};