一:题目
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{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;
}
二:题目分析
首先,我们知道前序表达式的第一个结点实际上就是整个二叉树的根结点,那么我们就可以根据这个根节点找到对应的中序遍历序列中根结点的位置。那么根据中序遍历的特点,我们知道根结点的左边序列是左子树,根节点的右边序列是右子树。这样我们就可以求出左子树的结点个数N,通过个数N来找前序遍历序列中的左子树:即除根结点后的N个数所组成的序列就是前序遍历序列中的左子树,剩余的就是右子树。
以上的前序遍历左子树序列、中序遍历左子树序列和前序遍历右子树序列、中序遍历右子树序列又可以作为新的输入来重建剩余的子树。这个过程完全可以使用递归的方法,知道找到最后一个结点作为输入。
综上可以按照如下的思路来重建二叉树:
- 根据前序遍历序列的第一个结点找对应中序遍历序列的根结点;
- 根据中序遍历序列的根结点,获取中序遍历序列的左子树序列和右子树序列;
- 根据中序遍历序列的左子树序列的结点数,获取前序遍历序列的左子树序列和右子树序列;
- 将前序遍历序列的左子树序列和中序遍历序列的左子树序列作为新的输入重复1-3的步骤;
- 将前序遍历序列的右子树序列和中序遍历序列的右子树序列作为新的输入重复1-3的步骤;
三:源码
Contruct(int* pPreorder, int* pInorder, int nLength) {
if (nullptr == pPreorder || nullptr == pInorder || nLength <= 0) {
return nullptr;
}
return ContructCore(pPreorder, pPreorder + nLength - 1, pInorder, pInorder + nLength - 1);
}
ContructCore(int* pStartPreorder, int* pEndPreorder, int* pStartInorder, int* pEndInorder) {
if (nullptr == pStartPreorder || nullptr == pEndPreorder || nullptr == pStartInorder || nullptr == pEndPreorder) {
return nullptr;
}
BinaryTreeNode* pRoot = new BinaryTreeNode;
pRoot->m_nValue = *pStartPreorder;
pRoot->m_pLeftTreeNode = nullptr;
pRoot->m_pRightTreeNode = nullptr;
if (pStartPreorder == pEndPreorder) {
if (pStartInorder == pEndInorder && *pStartInorder == *pStartPreorder) {
return pRoot;
}
else {
throw std::exception("Invalid input");
}
}
//find rootValue
int *pCurInorder = pStartInorder;
while (pCurInorder != pEndInorder) {
if (*pCurInorder == *pStartPreorder) {
break;
}
++pCurInorder;
}
if (pCurInorder == pEndInorder && *pCurInorder != *pStartPreorder) {
throw std::exception("Invalid input");
}
/*
inorder:
left subtree sequence: pStartInorder -> pCurInorder - 1
right subtree sequence: pCurInorder + 1 -> pEndInorder
*/
int nInorderLeftSubtreeLength = pCurInorder - pStartInorder;
/*
preorder:
left subtree sequence: pStartPreorder + 1 -> pEndPreorderLeftSubtree
right subtree sequence: pEndPreorderLeftSubtree + 1 -> pEndPreorder
*/
int* pEndPreorderLeftSubtree = pStartPreorder + nInorderLeftSubtreeLength;
if (nInorderLeftSubtreeLength > 0) {
pRoot->m_pLeftTreeNode = ContructCore(pStartPreorder + 1, pEndPreorderLeftSubtree, pStartInorder, pCurInorder - 1);
}
if (pEndPreorder - pEndPreorderLeftSubtree > 0) {
pRoot->m_pRightTreeNode = ContructCore(pEndPreorderLeftSubtree + 1, pEndPreorder, pCurInorder + 1, pEndInorder);
}
return pRoot;
}
三:测试
int nPreInorder[] = { 1, 2, 4, 7, 3, 5, 6, 8 };
int nInorder[] = { 4, 7, 2, 1, 5, 3, 8, 6 };
BinaryTreeNode* pRoot = Contruct(nPreInorder, nInorder, 8);