已知二叉树前序遍历和中序遍历的结果,重建二叉树

假设输入二叉树的前序遍历序列为{1,2,4,7,3,5,6,8},中序遍历序列{4,7,2,1,5,3,8,6}

思路:

首先由前序遍历序列可以找到根结点的值是第一个元素的值,然后去寻找中序遍历中根结点的位置在哪里,从而可以得到左子树的长度大小,可以确定前序遍历中左子树的终点位置在哪里,就可以重新构建左子树。同时,由中序遍历中根结点的位置和前序遍历中左子树的终点位置重构右子树。

代码实现如下:

struct BinaryTreeNode
{
int m_nValue;
BinaryTreeNode* m_pLeft;
BinaryTreeNode* m_pRight;

}

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



BinaryTreeNode* ConstructCore(int* startPreorder,int* endPreorder,int* startInorder,int* endInorder)
{
	int rootvalue=startPreorder[0];
	BinaryTreeNode* root=new BinaryTreeNode();
	root->m_nValue=rootvalue;
	root->m_pLeft=root->m_pRight=NULL;
	
	if(startPreorder==endPreorder)
	{
		if(startInorder==endInorder && *startPreorder==*startInorder)
			return root;
		else 
			throw std::exception("Invalid inout.");
	}
	//中序遍历中找到根结点的值
	int* rootInorder=startInorder;
	while(rootInorder<=endInorder && *rootInorder!=rootvalue)
		rootInorder++;
	if(rootInorder==endInorder && *rootInorder!=rootvalue)
		throw std::exception("Invalid input!");
	
	int leftlength=rootInorder-startInorder;
	int *leftPreorderEnd=startPreorder+leftlength;
	if(leftlength>0)
	{
		//构建左边子树
		root->m_pLeft=ConstructCore(startPreorder+1,leftPreorderEnd,startInorder,rootInorder-1);
	}
	if(leftlength<endPreorder-startPreorder)
	{
		//构建右边子树
		root->m_pRight=ConstructCore(leftPreorderEnd+1,PreorderEnd,rootInorder+1,endInorder);
	}
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值