/**
* 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* bulid(vector<int>& preorder,int l1,int r1,vector<int>& inorder,int l2,int r2)
{
if(l1>r1) return NULL;
int root=preorder[l1];
int idx=-1;
for (int i = l2; i <= r2; i ++ )
if(inorder[i]==root)
{
idx=i;
break;
}
TreeNode* t=new TreeNode(root);
int len=idx-l2;//左子树长度
t->left=bulid(preorder,l1+1,l1+len,inorder,l2,idx-1);
t->right=bulid(preorder,l1+len+1,r1,inorder,idx+1,r2);
return t;
}
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
TreeNode* root=bulid(preorder,0,preorder.size()-1,inorder,0,preorder.size()-1);
return root;
}
};
标签:preorder,bulid,TreeNode,int,二叉树,l1,inorder,重建
From: https://www.cnblogs.com/tangxibomb/p/17210588.html