struct TreeNode{
int value;
TreeNode* left;
TreeNode* right;
};
TreeNode* construct(int* preorder,int* inorder,int len){
//两个序列都不能为空,长度不能为负数
if(preorder==NULL||inorder||NULL||len<=0){
return NULL;
}
return constructcore(preorder,preorder+len-1,inorder,inorder+len-1)
}
TreeNode* constructcore(int* prestart,int* preend,int* instart,int* inend){
//创建根节点
TreeNode* root=new TreeNode();
root->left=root->right=NULL;
root->value=*prestart;
//判断只有一个节点的情况,递归的尽头就是一个节点的情况,之后的代码不能处理这种情况
if(prestart==preend){
if(instart==inend&&*prestart==*instart){
return root;
}
else
throw std::exception("invalid input.");
}
//在inorder中找到root
/*
int cntleft=0;
while(*(instart+cntleft)!=*prestart&&(instart+cntleft)<inend){
++cntleft;
}
if(cntleft==inend-instart&&*(instart+cntleft)!=*prestart){
//return NULL;
throw std::exception("invalid input.");
}
*/
int* inroot=instart;
while(*inroot!=*prestart&&inroot<=inend){//<= should be < ?
inroot++;
}
if(inroot==inend&&*inroot!=*prestart){
throw std::exception("invalid input.");
}
//左子树节点的个数
int leftlen=inroot-instart;
//构建左子树
if(leftlen>0){
root->left=constructcore(prestart+1,prestart+leftlen,instart,inroot-1);
}
//构建右子树
if(prestart+leftlen<preend){
root->right=constructcore(prestart+leftlen+1,preend,inroot+1,inend);
}
/*
root->left=constructcore(prestart+1,prestart+1+cntleft,instart,instart+cntleft);
root->right=constrctcore(prestart+2+cntleft,preend,instart+cntleft+2,inend);
*/
//返回根节点
return root;
}
剑指offer 面试题6 重建二叉树
最新推荐文章于 2020-11-27 20:09:49 发布