zoukankan      html  css  js  c++  java
  • 从先序中序重建二叉树输出层序后序

    #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;
    }
  • 相关阅读:
    第五章 Internet协议
    第四章 地址解析协议
    Learn the shell
    Linux学习前的准备
    第三章 链路层
    第二章 Internet 地址结构
    后台数据导出为Excel
    C#开发客户端、JAVA和tomcat开发服务端
    Java基础
    C++学习笔记--(1)
  • 原文地址:https://www.cnblogs.com/syzyaa/p/14135233.html
Copyright © 2011-2022 走看看