题目: 输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。
解题思路:递归实现
/**********************
* 面试题6 : 重建二叉树
***********************/
struct BinaryTreeNode
{
int Value;
BinaryTreeNode* pLeft;
BinaryTreeNode* 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->Value = rootValue;
root->pLeft = root->pRight = NULL;
if(startPreorder == endPreorder)
{
if(startInorder = endInorder
&& *startPreorder == *startInorder)
return root;
else
throw exception("Invalid input");
}
// 在中序遍历序列中找到根节点的值
int* rootInorder = startInorder;
while(rootInorder <= endInorder && *rootInorder != rootValue)
{
++rootInorder;
}
if(rootInorder == endInorder && *rootInorder != rootValue)
{
throw exception("Invalid input");
}
int leftLength = rootInorder - startInorder;
int* leftPreorderEnd = startPreorder +leftLength;
if(leftLength > 0)
{
//构建左子树
root->pLeft = ConstructCore(startPreoder + 1,
leftPreorderEnd, startInorder, rootInorder -1);
}
if(leftLength < endPreorder - startPreorder)
{
//构建右子树
root->pRight = ConstructCore(leftPreorderEnd + 1,
endPreorder, rootInorder + 1, endInorder);
}
return root;
}