/*****************************************************************
题目:输入某二叉树的前序遍历和中序遍历的结果,请重新建出该二叉树。
假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序
序列{1,2,4,7,3,5,6,8}和中序序列{4,7,2,1,5,3,8,6},则重建出如图所示的
二叉树。二叉树的定义如下:
1
/ \
2 3
/ / \
4 5 6
\ /
7 8
******************************************************************/
#include<stdio.h>
#include<iostream>
struct BinaryTreeNode
{
int m_nKey;
BinaryTreeNode* m_pLeft;
BinaryTreeNode* m_pRight;
};
BinaryTreeNode* createBinaryTreeNode(int value)
{
BinaryTreeNode* pNode = new BinaryTreeNode();
pNode->m_nKey = value;
pNode->m_pLeft = NULL;
pNode->m_pRight = NULL;
return pNode;
}
void connectBinaryTreeNode(BinaryTreeNode* pParent,BinaryTreeNode* pLeft,BinaryTreeNode* pRight)
{
if(pParent)
{
pParent->m_pLeft = pLeft;
pParent->m_pRight = pRight;
}
}
void destroyBinaryTree(BinaryTreeNode* pRoot)
{
if(pRoot)
{
BinaryTreeNode* pLeft = pRoot->m_pLeft;
BinaryTreeNode* pRight = pRoot->m_pRight;
delete pRoot;
destroyBinaryTree(pLeft);
destroyBinaryTree(pRight);
}
}
BinaryTreeNode* concreteBinaryTree(int* preOrder,int* midOrder,int length)
{
if(preOrder && midOrder && length != 0)
{
int i = 0;
for(i=0; i<length; i++)
{
if(preOrder[0] == midOrder[i])
break;
}
if(i>=length) //如果在中序排列队列中找不到根节点,抛出异常
throw std::exception("Invalid input");
BinaryTreeNode* pNode = createBinaryTreeNode(preOrder[0]);
if(i > 0)
pNode->m_pLeft = concreteBinaryTree(preOrder+1,midOrder,i);
if(length-1-i > 0)
pNode->m_pRight = concreteBinaryTree(preOrder+i+1,midOrder+i+1,length-1-i);
return pNode;
}
else
return NULL;
}
void pre_Order(BinaryTreeNode* pRoot)
{
if(pRoot)
{
printf("%d\t",pRoot->m_nKey);
pre_Order(pRoot->m_pLeft);
pre_Order(pRoot->m_pRight);
}
}
void mid_Order(BinaryTreeNode* pRoot)
{
if(pRoot)
{
mid_Order(pRoot->m_pLeft);
printf("%d\t",pRoot->m_nKey);
mid_Order(pRoot->m_pRight);
}
}
void test()
{
const int length = 8;
int preOrder[8] = {1,2,4,7,3,5,6,8};
int midOrder[8] = {4,7,2,1,5,3,8,6};
BinaryTreeNode* pNode1 = concreteBinaryTree(preOrder,midOrder,length);
pre_Order(pNode1);
printf("\n");
mid_Order(pNode1);
}
int main()
{
test();
return 0;
}
/*
首先根据前序遍历序列的第一个数字创建根节点,接下来在中序遍历序列
中找到根节点位置,这样就能确定左右字数节点的数量。在前序和中序遍
历的序列中划分了左、右子数的节点的值之和,我们就可以递归地调用函
数concreteBinaryTree,去分别构建它的左、右子树。
*/
BinaryTreeNode* reBuildBinaryTree( int arr1[], int arr2[], int len)
{
if(arr1 && arr2 && len>0)
{
BinaryTreeNode* pRoot = new BinaryTreeNode();
pRoot->m_nValue = arr1[0];
pRoot->m_pLeft = NULL;
pRoot->m_pRight = NULL;
int i=0;
while(i<len && arr2[i]!=arr1[0])
++i;
if(i!=len){
if(i>0)
pRoot->m_pLeft = reBulidBinaryTree(arr1+1, arr2, i);
if(len-i-1 > 0)
proot->m_pRight = reBuildBinaryTree(arr+i+1, arr2+i+1, len-i-1);
return pRoot;
}
else
{
throw std::exception("invalid input!");
}
}
throw std::exception("invalid input!");
}