• [二叉树建树] 复原二叉树(层序和中序)


    题目描述

    给一棵二叉树的层序遍历序列和中序遍历序列,求这棵二叉树的先序遍历序列和后序遍历序列。

    输入

    每个输入文件中一组数据。

    第一行一个正整数N(1<=N<=30),代表二叉树的结点个数(结点编号为1~N)。接下来两行,每行N个正整数,分别代表二叉树的层序遍历序列和中序遍历序列。数据保证序列中1~N的每个数出现且只出现一次。

    输出

    输出两行,每行N个正整数,分别代表二叉树的先序遍历序列和后序遍历序列。每行末尾不输出额外的空格。

    样例输入

    7
    3 5 4 2 6 7 1
    2 5 3 6 4 7 1

    样例输出

    3 5 2 4 6 7 1
    2 5 6 1 7 4 3
    #include <iostream>
    #include <cstdio>
    #include <cmath>
    #include <cstring>
    #include <algorithm>
    #include <vector>
    #include <map>
    #include <queue>
    using namespace std;
    
    const int maxn=1000000;
    struct Node
    {
        int data;
        Node *l,*r;
    };
    
    int layer[maxn];
    int in[maxn];
    
    int n;
    
    vector<int> ans;
    
    void creat(Node * & root,int data,int index)
    {
        if(root==NULL)
        {
            root=new Node;
            root->l=NULL;
            root->r=NULL;
            root->data=data;
            //cout<<"end---"<<endl;
            return ;
        }
        int u;
        for(u=0;u<n;u++)
        {
            if(in[u]==root->data) break;
        }
        if(u<index) creat(root->r,data,index);
        else creat(root->l,data,index);
    }
    
    void pre(Node * root)
    {
        if(root!=NULL)
        {
            ans.push_back(root->data);
            pre(root->l);
            pre(root->r);
        }
    }
    
    void outans()
    {
        for(int i=0;i<ans.size();i++)
        {
            if(i>0) cout<<" ";
            cout<<ans[i];
        }
        cout<<endl;
    }
    
    void post(Node * root){
        if(root!=NULL)
        {
            post(root->l);
            post(root->r);
            ans.push_back(root->data);
        }
    }
    
    int main()
    {
        cin>>n;
        for(int i=0;i<n;i++) cin>>layer[i];
        for(int i=0;i<n;i++) cin>>in[i];
        Node * root=NULL;
        for(int i=0;i<n;i++)
        {
            int u;
            for(u=0;u<n;u++)
            {
                if(in[u]==layer[i]) break;
            }
            creat(root,layer[i],u);
        }
        ans.clear();
        pre(root);
        outans();
        ans.clear();
        post(root);
        outans();
    }
  • 相关阅读:
    按钮,文本框
    d01
    第一天,对于课程和工作的了解
    javaweb概念性知识
    Jdbc概念性知识
    连接数据库,和数据增删改
    oracle基础概念性知识
    面向对象java知识汇总题
    javaweb
    date日期
  • 原文地址:https://www.cnblogs.com/xiongmao-cpp/p/6481130.html
Copyright © 2020-2023  润新知