【算法题】重建二叉树

来源:互联网 发布:淘宝优优管家是真的吗 编辑:程序博客网 时间:2024/06/14 16:47

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



#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;}
原创粉丝点击