如果不确定范围可以自己画图解释
class Solution {
public:
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
TreeNode* root = build(preorder,inorder,0,preorder.size()-1,0,inorder.size()-1);
return root;
}
TreeNode* build(vector<int>& preorder,vector<int>& inorder,int preL,int preR,int inL,int inR){
if(preL>preR||inL>inR) return NULL;
TreeNode* root = new TreeNode(preorder[preL]);
//root->val = preorder[preL];
int leftlen = 0;
for(int i = inL;i<=inR;i++){
if(inorder[i]==preorder[preL]){
leftlen = i - inL;
break;
}
}
root->left = build(preorder,inorder,preL+1,preL+1+leftlen-1,inL,inL+leftlen-1);
root->right = build(preorder,inorder,preL+leftlen+1,preR,inL+leftlen+1,inR);
return root;
}
};
LeetCode 105. 从前序与中序遍历序列构造二叉树(C++)
原文:https://www.cnblogs.com/shuibeng/p/13626914.html