• 从先序中序重建二叉树输出层序后序


    #include <iostream>
    #include <vector>
    #include <string>
    #include <queue>
    #include <cstring>
    #define MAX 10000
    using namespace std;
    
    struct tree
    {
        int data;
        tree* left;
        tree* right;
        tree()
        {
            data = 0;
            left = NULL;
            right = NULL;
        }
    };
    tree* root;
    int front[100000];
    int mid[100000];
    int n;
    tree* build(int *front,int *mid,int n)
    {
        if(n == 0)
            return NULL;
        int x = 0;
        while(front[0]!=mid[x])
            x++;
        tree *t = new tree();
        t->data = mid[x];
        t->left = build(front+1,mid,x);
        t->right = build(front+1+x,mid+1+x,n-x-1);
        return t;
    }
    
    void order(tree* t)
    {
        queue<tree *> tmp;
        tmp.push(t);
        while(!tmp.empty())
        {
            tree * tt;
            tt = tmp.front();
            tmp.pop();
            cout<<tt->data<<" ";
            if(tt->left != NULL)
                tmp.push(tt->left);
            if(tt->right != NULL)
                tmp.push(tt->right);
        }
    }
    void PostOrder(tree* t)
    {
        if(t)
        {
            PostOrder(t->left);
            PostOrder(t->right);
            cout<<t->data<<" ";
        }
    }
    int main()
    {
        cin>>n;
        for (int i = 0; i < n; ++i)
            cin>>front[i];
        for (int i = 0; i < n; ++i)
            cin>>mid[i];
        root = build(front,mid,n);
        order(root);
        cout<<endl;
        PostOrder(root);
        return 0;
    }
  • 相关阅读:
    数据存储检索之B+树和LSM-Tree
    Kylin构建Cube过程详解
    关于maven打包乱码报错问题解决
    很详尽KMP算法 转载
    计算机源码反码补码
    Lombok实现链式编程 转载
    java适配器模式
    ubuntu卸载软件步骤(转)
    JMeter压测的使用
    @valid注解的使用(转载)
  • 原文地址:https://www.cnblogs.com/syzyaa/p/14135233.html
Copyright © 2020-2023  润新知