递归调用实现左右子树的分类
先序的第一个为根结点,然后找中序中根结点的位置,这样根结点左边的即为左子树,右边的即右子树,然后重复调用,把每个左子树又看作是完整的树
自己看的别人,然后重新写出来的
class Solution {
public:
TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> in) {
int length=in.size();
if(length==0)return NULL;
vector<int> pre_left,pre_right,in_left,in_right;
TreeNode* head=new TreeNode(pre[0]);
int root=0;
for(int i=0;i<length;i++)
{
if(in[i]==pre[0])
{
root=i;
break;
}
}
for(int i=0;i<root;i++)
{
in_left.push_back(in[i]);
pre_left.push_back(pre[i+1]);
}
for(int i=root+1;i<length;i++)
{
in_right.push_back(in[i]);
pre_right.push_back(pre[i]);
}
head->left=reConstructBinaryTree(pre_left,in_left);
head->right=reConstructBinaryTree(pre_right,in_right);
return head;
}
};