输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建出它的二叉树,并输出它的头结点。
#include <stdio.h>
#include <iostream>
using namespace std;
struct BinaryTreeNode
{
int m_Value;
BinaryTreeNode* m_Left;
BinaryTreeNode* m_Right;
};
//构建树
BinaryTreeNode* ConstructCore(int* startPreorder, int* endPreorder, int* startInorder, int* endInorder)
{
//前序遍历序列的第一个数字是根节点的值
int rootValue = startPreorder[0];
BinaryTreeNode* root = new BinaryTreeNode(); //创建一个节点
root->m_Value = rootValue;
root->m_Left = root->m_Left = NULL;
if (startPreorder == endPreorder) //判断是否是叶子节点
{
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 = startPreorder + leftLength; //取得在前序遍历中左子树结束的位置
if (leftLength > 0) //判断是否有左子树
{
//构建左子树
root->m_Left = ConstructCore(startPreorder + 1, leftPreorderEnd, startInorder, rootInorder - 1);
}
if (leftLength < endPreorder - startPreorder) //总数-左子树数 来判断是否有右子树
{
//构建右子树
root->m_Right = ConstructCore(leftPreorderEnd + 1, endPreorder, rootInorder + 1, endInorder);
}
return root;
}
//判断是否满足条件
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);
}
//后序遍历
void backTraverse(BinaryTreeNode* root)
{
if (root == NULL)
return;
backTraverse(root->m_Left);
backTraverse(root->m_Right);
cout << root->m_Value;
}
int main(int argc,char *argv[])
{
int preOrder[8] = { 1, 2, 4, 7, 3, 5, 6, 8 };
int inOrder[8] = { 4, 7, 2, 1, 5, 3, 8, 6 };
BinaryTreeNode* root = Construct(preOrder, inOrder, 8);
backTraverse(root);
return 0;
}