根据前序和中序遍历结果构造二叉树

思路:前序第一个元素作为根,从中序找出左子树和右子树的序列,递归构建子树

TreeNode * Construct(int * preOrder,int * inOrder,int length)
{//根据前序和中序构造二叉树
	if (preOrder==NULL||inOrder==NULL||length<=0)
	{
		return NULL;
	}

	return ConstructCore(preOrder,preOrder+length-1,inOrder,inOrder+length-1);

}

TreeNode * ConstructCore(int* startPreOrder,int* endPreOrder,int* startInOrder,int* endInOrder)
{
	int rootValue=startPreOrder[0];
	TreeNode* root=new TreeNode();
	root->value=rootValue;
	root->lchild=root->rchild=NULL;

	if (startPreOrder==endPreOrder)
		if (startInOrder==endInOrder&&(*startPreOrder)==(*startInOrder))
		{
			return root;
		}
		else throw std::exception("error");

	//寻找根在中序中的位置
	int * rootInOrder=startInOrder;
	while(rootInOrder<=endInOrder&&*rootInOrder!=rootValue) rootInOrder++;
	if (rootInOrder==endInOrder&&*rootInOrder!=*endInOrder) throw std::exception("error");

	int leftLength=rootInOrder-startInOrder;
	int rightLength=endInOrder-rootInOrder;
	
	int* leftEndPreOrder=startPreOrder+leftLength;
	int* rightStartPreOrder=leftEndPreOrder+1;
	
	if (leftLength>0)
	{//构建左子树
		root->lchild=ConstructCore(startPreOrder+1,leftEndPreOrder,startInOrder,rootInOrder-1);
	}
	if (rightLength>0)
	{
		root->rchild=ConstructCore(rightStartPreOrder,endPreOrder,rootInOrder+1,endInOrder);
	}
	return root;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值