【算法题】重建二叉树

已知先序遍历和中序遍历,重建二叉树



#include <iostream>
#include <numeric>
#include<algorithm>
using namespace std;

struct Tree
{
    double value;
    Tree* left;
    Tree* right;
};

void Print(Tree* root)
{
    if (root == NULL)
        return;

    queue<Tree*> queue_current;
    queue<Tree*> queue_next;

    auto * p_current = &queue_current;
    auto * p_next = &queue_next;

    Tree* p = root;
    p_next->push(p);

    while (!(*p_next).empty())
    {
        std::swap(p_current, p_next);
        while (!(*p_current).empty())
        {
            p = p_current->front();
            p_current->pop();
            cout << p->value << " ";
            if (p->left != NULL)
            {
                p_next->push(p->left);
            }
            if (p->right != NULL)
            {
                p_next->push(p->right);
            }
        }
        cout << endl;
    }
}

Tree* ReconstructCore(int* prestart, int * preend, int * midstart, int * midend)
{

    Tree * tmp;
    tmp = new Tree;
    tmp->value = *prestart;

    int c = find(midstart, midend + 1, *prestart) - midstart;
    if (c != 0)
    {
        tmp->left = ReconstructCore(prestart + 1, prestart + c,midstart,midstart+c-1);
    }
    else
    {
        tmp->left = NULL;
    }
    if (midstart + c != midend)
    {
        tmp->right = ReconstructCore(prestart+c+1,preend,midstart+c+1,midend );
    }
    else
    {
        tmp->right = NULL;
    }

    return tmp;
}

Tree* Reconstruct(int* pre, int* mid,int len)
{
    if (pre == NULL || mid == NULL || len <= 0)
        return NULL;
    return ReconstructCore(pre, pre + len - 1, mid, mid + len - 1);
}

int main()
{
    int pre[8]{ 1, 2, 4, 7, 3, 5, 6, 8 };
    int mid[8]{ 4, 7, 2, 1, 5, 3, 8, 6 };

    Tree *root = Reconstruct(pre, mid,8);

    Print(root);

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值