重建二叉树
/*
* 二叉树的遍历方式:
* 前序遍历:先访问根节点,再访问左子节点,最后访问右子节点。
* 中序遍历:先访问左子节点,再访问根节点,最后访问右子节点。
* 后序遍历:先访问左子节点,再访问右子节点,最后访问根节点。
*/
/*
* 输入二叉树的前序遍历和中序遍历的结果,请重新构建该二叉树。
* 假设前序遍历和中序遍历的结果中都不含重复的数字。例如输入
* 的前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},
* 则构建出所对应的二叉树,并返回根节点。
*/
/*
* 在二叉树的前序遍历序列中,第一个数字总是树的根节点的值。在中序遍历中,
* 根节点的值在序列的中间,左子树的节点的值位于根节点值的左边,右子树的节点的
* 值位于根结点的值的右边。
*/
#include<iostream>
using namespace std;
struct BinaryTreeNode
{
int m_nValue;
BinaryTreeNode* m_pLeft;
BinaryTreeNode* m_pRight;
};
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 = nullptr;
if (startPreorder == endPreorder)
{
if (startInorder == endInorder && *startPreorder == *endPreorder)
{
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 = 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, endPreorder, rootInorder + 1, endInorder);
}
return root;
}
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);
}
int main()
{
int preOrder[] = { 1,2,4,7,3,5,6,8 };
int inOrder[] = { 4,7,2,1,5,3,8,6 };
BinaryTreeNode* root = Construct(preOrder, inOrder, 8);
return 0;
}
posted on 2021-11-11 08:25 xcxfury001 阅读(18) 评论(0) 收藏 举报
浙公网安备 33010602011771号