重建二叉树

题目6:重建二叉树

题目:输入某二叉树的前序遍历和中序遍历的结果,重建出该二叉树。


解题的过程:


我们知道根据二叉树的前序或者后序遍历的结果,加上中序遍历的结果便可以还原出这棵二叉树。

例如:前序序列为:

12345678
中序序列为:

47215386
我们知道前序序列是根节点的位置,因此扫描到1时可以判断1是根节点。然后再扫描中序序列,在遇到1之前的部分都为左孩子,其余的为右孩子。确定了根节点、左右子树后再继续重建二叉树。现在已经确定了根节点为1.左子树为:4、7、2右子树为:5、3、8、6。再次扫描前序序列第二元素为2,则2为左子树的根节点,同样的再次扫描中序序列在遇到2之前的都为左子树,其余的为右子树。注意:这里的结束条件,刚开始的时候就是这里出了问题,第一次遍历的时候就确定了左右子树的节点数,这里就是用这个作为判断结束的条件。

BinaryTreeNode * 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);
}

BinaryTreeeNoe * ConstructCore
(int * startPreorder,int * endPreorder,int * startInorder,int * endInorder)
{
	int rootValue = startPreorder[0];
	BinaryTreeNode * root = new BinaryTreeNode();
	root->value = rootValue;
	root->Left = root->Right=null;

	if(startPreorder == endPreorder)
	{
		if(startInorder == endInorder && *startPreoder==*startInorder)
		{
			return root;
		}
		else
		{
			exception("error");
		}
	}

	//在中序遍历中找到根节点的值

	int * rootInorder = startInorder;
	while(rootInorder <= endInorder && *rootInorder != rootValue)
	{
		++ rootInorder;
	}

	if(rootInorder == endInorder && *rootInorder != rootValue)
	{
		exception("error");
	}

	int leftLength = rootInorder - startInorder;
	int * leftPreorderEnd = startInorder +leftLength;

	if(leftLength>0)
	{
		//构建左子树
		root->Left = ConstructCore(startPreorder+1,leftPreorderEnd,startInorder,rootInorder -1);
	}

	if(leftLength<endPreorder-startPreorder)
	{
		//	构建右子树
		root->Right = ConstructCore(leftPreorderEnd+1,endPreorder,rootInorder+1,endInorder);
	}

	return root;
}

现在理解的还不是太透彻继续领悟。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值