zoukankan      html  css  js  c++  java
  • [二叉树建树] 复原二叉树(层序和中序)

    题目描述

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

    输入

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

    第一行一个正整数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();
    }
  • 相关阅读:
    Java 泛型 泛型的约束与局限性
    Java 泛型 泛型方法
    Java 泛型 泛型数组
    Java 泛型 协变性、逆变性
    Java 泛型 协变式覆盖和泛型重载
    Java 泛型 泛型代码和虚拟机
    Insertion Sort List
    Remove Duplicates from Sorted List II
    String to Integer (atoi)
    SpringMvc源码入门
  • 原文地址:https://www.cnblogs.com/xiongmao-cpp/p/6481130.html
Copyright © 2011-2022 走看看