剑指offer 面试题6 重建二叉树

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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值