题目:输入某二叉树的前序遍历和中序遍历的结果,请重建该二叉树。假设输入的前序序列和中序序列中都不含重复的数字。
例如输入前序{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6}
重建二叉树如图所示(省略)。二叉树节点的定义如下:
struct BinaryTreeNode
{
int mValue;
BinaryTreeNode* mLeftChild;
BinaryTreeNode* mRightChild;
};
#include <iostream>
using namespace std;
struct BinaryTreeNode
{
char mValue;
BinaryTreeNode * mLeftChild;
BinaryTreeNode * mRightChild;
};
//我写的版本
BinaryTreeNode* Construct0(char * preOrder , char * inOrder, int length)
{
if (length <= 0)
return NULL;
BinaryTreeNode* root = new BinaryTreeNode();
root->mValue = preOrder[0];
root->mLeftChild = NULL;
root->mRightChild = NULL;
int i = 0;
for (i; i < length && preOrder[0] != inOrder[i]; ++i);
int leftLength = i;
int rightLength = length - leftLength - 1;
root->mLeftChild = Construct0(preOrder + 1, inOrder, leftLength);
root->mRightChild = Construct0(preOrder + 1 + leftLength, inOrder + 1 + leftLength, rightLength);
return root;
}
void PostOrder(BinaryTreeNode * root)
{
if (root)
{
PostOrder(root->mLeftChild);
PostOrder(root->mRightChild);
cout << root->mValue << " ";
}
}
int main()
{
BinaryTreeNode * root = NULL;
root = Construct0("12473568","47215386", 8);
PostOrder(root);
return 0;