中序遍历中根节点前的节点为左子树,根节点后的节点为右子树。
class Soultion{
public:
struct TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> in) {
int inlen=in.size();
if(inlen==0)
return NULL;
vector<int>left_pre,right_pre,left_in,right_in;
//创建根节点,前序遍历的第一个数
TreeNode* head=new TreeNode(pre[0]);
//找到中序遍历根节点的位置
int gen=0;
for(int i=0;i<inlen;i++){
if(in[i]==pre[0]){
gen=i;
break;
}
}
//在中序遍历中,根节点前的点为左子树,后边的点为右子树
for(int i=0;i<gen;i++){
left_in.push_back(in[i]);
left_pre.push_back(pre[i+1]);
}
for(int i=gen+1;i<inlen;i++){
right_in.push_back(in[i]);
right_pre.push_back(pre[i]);
}
head->left=reConstructBinaryTree(left_pre,left_in);
head->right=reConstructBinaryTree(right_pre,right_in);
return head;
};