题目:输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数组。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},重建出图所示的二叉树并输出 它的头结点。
二叉树节点的定义如下:
先序遍历序列的第一个元素为根rootValue,其后依次为左子树部分和右子树部分。
中序遍历序列中寻找根rootValue的位置,则其左边为左子树部分,右边为右子树部分。
考虑使用递归:构造左右子树(可能为空树),然后依照左右子树构造根节点
图示如下所示:
二叉树节点的定义如下:
struct BinaryTreeNode{
int m_nValue;
BinaryTreeNode *m_pLeft;
BinaryTreeNode *m_pRight;
};
思路:
先序遍历序列的第一个元素为根rootValue,其后依次为左子树部分和右子树部分。
中序遍历序列中寻找根rootValue的位置,则其左边为左子树部分,右边为右子树部分。
考虑使用递归:构造左右子树(可能为空树),然后依照左右子树构造根节点
图示如下所示:
编译环境:ArchLinux+Clang3.3,C++11
算法实现:
#include <iostream>
#include <stdexcept>
using namespace std;
struct BinaryTreeNode{
int m_nValue;
BinaryTreeNode *m_pLeft;
BinaryTreeNode *m_pRight;
};
/* 范围:[begin, end) */
BinaryTreeNode *create(int *begin1, int *end1, int *begin2, int *end2)
{
if (begin1>=end1) return nullptr;
int rootValue1 = *begin1;
int *rootPtr2 = begin2; // rootValue1在中序中的位置
while (rootPtr2 < end2 && *rootPtr2 != rootValue1)
rootPtr2++;
if (rootPtr2 == end2 || end1-begin1 != end2-begin2) // 输入参数合法性检查,尽管第二个条件可放在函数开始处,但这样更一致
throw std::invalid_argument("Invalid input.");
/** 构建左右子树并构建根节点 **/
return new BinaryTreeNode{rootValue1,
create(begin1+1, begin1+(rootPtr2-begin2)+1, begin2, rootPtr2),
create(begin1+(rootPtr2-begin2)+1, end1, rootPtr2+1, end2)
};
}
/** 以root(left,right)的嵌套形式打印二叉树 **/
void print(BinaryTreeNode *root)
{
if (root == nullptr ){
cout <<"()";
return;
}
cout << root->m_nValue;
cout << '(';
if (root->m_pLeft) print(root->m_pLeft);
cout << ',';
if (root->m_pRight) print(root->m_pRight);
cout << ')';
}
int main()
{
int a[] = {1,2,4,7,3,5,6,8};
int b[] = {4,7,2,1,5,3,8,6};
BinaryTreeNode *root = create(a, a+sizeof(a)/sizeof(int), b, b+sizeof(b)/sizeof(int));
print(root);
cout << endl;
}