# [leetcode]105. Construct Binary Tree from Preorder and Inorder Traversal

/**
* 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) {
int len=preorder.size();
if(len==0)
return {};
else
return build(preorder,inorder,0,len-1,0,len-1);
}
TreeNode* build(vector<int>& preorder, vector<int>& inorder,int preL,int preR,int inL,int inR)
{
if(preR<preL||inR<inL)
return {};

TreeNode* root=new TreeNode(preorder[preL]);
if(preR==preL||inR==inL)
return root;

int mid;
for(int i=inL;i<=inR;i++)
{
if(inorder[i]==preorder[preL])
{
mid=i;
break;
}
}
root->left=build(preorder,inorder,preL+1,preL+mid-inL,inL,mid-1);
root->right=build(preorder,inorder,preL+1+mid-inL,preR,mid+1,inR);
return root;

}
};



• 本文已收录于以下专栏：

举报原因： 您举报文章：[leetcode]105. Construct Binary Tree from Preorder and Inorder Traversal 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)