• 数据结构实习


    用前序中序建立二叉树并以层序遍历和后序遍历输出

    writer:pprp

    实现过程主要是通过递归,进行分解得到结果
    代码如下:
    #include <iostream>
    #include <queue>
    #include <cstdio>
    #include <cstring>
    using namespace std;
    const int N = 1000;
    struct tree
    {
        tree* l;
        tree* r;
        int data;
        tree()
        {
            l = NULL;
            r = NULL;
            data = 0;
        }
    };
    void LevelOrder(tree * root)
    {
        queue<tree*> q;
        tree * p = root;
        q.push(p);
        while(!q.empty())
        {
            p = q.front();
            q.pop();
            cout << p->data << " ";
            if(p->l != NULL)
                q.push(p->l);
            if(p->r != NULL)
                q.push(p->r);
        }
    }
    
    void PostOrder(tree * root)
    {
        if(root != NULL)
        {
            PostOrder(root->l);
            PostOrder(root->r);
            cout << root->data << " ";
        }
    }
    
    tree * CreateTree(int* pre, int* in, int n)
    {
        tree * node = NULL;
        int lpre[N], rpre[N];
        int lin[N],rin[N];
        memset(lin,0,sizeof(lin)),memset(rin,0,sizeof(rin)),
               memset(lpre,0,sizeof(lpre)),memset(rpre,0,sizeof(rpre));
        if(n == 0)
            return NULL;
        node = new tree;
        node->data = pre[1];
        int lincnt = 1, rincnt = 1;
        int lprecnt = 1, rprecnt = 1;
    // deal with in order
        for(int i = 1; i <= n ; i++)
        {
            if(in[i]!=pre[1])
            {
                if(i <= lincnt)
                    lin[lincnt++] = in[i];
                else
                    rin[rincnt++] = in[i];
            }
        }
        lincnt--,rincnt--;
    // deal with pre order
        for(int i = 2; i <= n ; i++)
        {
            if(i < (lincnt+2))
                lpre[lprecnt++] = pre[i];
            else
                rpre[rprecnt++] = pre[i];
        }
        lprecnt--,rprecnt--;
        node->l = CreateTree(lpre,lin,lincnt);
        node->r = CreateTree(rpre,rin,rincnt);
        return node;
    }
    int main()
    {
        int n;
        cin >> n;
        int *pre, *in;
        pre = new int[n+1];
        in = new int[n+1];
        for(int i = 1; i <= n ; i++)
            cin >> pre[i];
        for(int i = 1; i <= n ; i++)
            cin >> in[i];
        tree * root = CreateTree(pre,in,n);
        LevelOrder(root);
        cout << endl;
        PostOrder(root);
        return 0;
    }
    
    
  • 相关阅读:
    二叉树遍历
    keras简单介绍与使用
    pandas基础使用
    如何在真机装linux(本人在台式机上又添了个硬盘)
    linux下安装kears
    Java Web 环境搭建步骤(超详细,包括前期安装步骤)
    python求范数
    随笔
    【opencv C++ linux】linux下编译含opencv的C++代码
    【论文阅读】DCAN: Deep Contour-Aware Networks for Accurate Gland Segmentation
  • 原文地址:https://www.cnblogs.com/pprp/p/7725499.html
Copyright © 2020-2023  润新知