剑指Offer算法实现之六:重建二叉树

题目:输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数组。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},重建出图所示的二叉树并输出 它的头结点。

二叉树节点的定义如下:
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;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值