zoukankan      html  css  js  c++  java
  • 数据结构实习

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

    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;
    }
    
    
  • 相关阅读:
    linux上用selenium登录新浪微博,获取用户关注的用户id
    JS、Python对字符串的编码函数
    在ubuntu系统下装hadoop
    windows下python3.x的安装与使用
    python多线程、多进程、协程的使用
    python简单操作redis
    操作系统基础知识
    排序算法汇总
    网易的突然袭击
    小红书视频面试
  • 原文地址:https://www.cnblogs.com/pprp/p/7725499.html
Copyright © 2011-2022 走看看