《剑指offer》面试题7:重建二叉树

题目:输入某二叉树的前序遍历和中序遍历的结果,请重建该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。

二叉树节点的定义如下:

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

在想清楚如何在前序遍历和中序遍历序列中确定左、右子树的子序列之后,可以写出如下的递归代码:

BinaryTreeNode* Construct(int* preorder,int* inorder,int length)
{
	if(preorder==nullptr || inorder==nullptr || length<=0)  return nullptr;
	return ConstructCore(preorder,preorder+length-1,inorder,inorder+length-1);
}

BinaryTreeNode*  ConstructCore(itn* startPreorder,int* endPreoder,int* startInorder,int* endInorder)
{
	//前序遍历序列的第一数字是根节点的值
	int rootValue=startPreorder[0];
	BinaryTreeNode* root=new BinaryTreeNode();
	root->m_nValue=rootValue;
	root->m_pLeft=root->m_pRight=nullptr;

	//前序遍历序列只有根节点一个数值
	if(startPreorder==endPreoder)
	{
		if(startInorder==endInorder && *startPreorder==*startInorder)
			return root;
		else
			throw std::exception("Invalid input.");
		
	}

	//在中序遍历序列中找到根节点的值
	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=startInorder+leftLength;
	if(leftLength>0)
	{
		//构建左子树
		root->m_pLeft= ConstructCore(startPreorder+1,leftPreorderEnd,startInorder,rootInorder-1);
	}
	if(leftLength<endPreoder-startPreorder)
	{
		//构建右子树
		root->m_pRight= ConstructCore(leftPreorderEnd+1,endPreoder,rootInorder+1,endInorder);
	}

	return root;
}

测试用例
a.普通二叉树(完全二叉树;不完全二叉树)。
b.特殊二叉树(所有节点都没有有子节点的二叉树;所有节点都没有左子节点的二叉树;只有一个节点的二叉树)。
c.特殊输入测试(二叉树的根节点指针为nullptr ;输入的前序遍历序列和中序遍历序列不匹配)。

猜你喜欢

转载自blog.csdn.net/qq_43502142/article/details/84562511