zoukankan      html  css  js  c++  java
  • PAT L2-011 玩转二叉树

    https://pintia.cn/problem-sets/994805046380707840/problems/994805065406070784

    给定一棵二叉树的中序遍历和前序遍历,请你先将树做个镜面反转,再输出反转后的层序遍历的序列。所谓镜面反转,是指将所有非叶结点的左右孩子对换。这里假设键值都是互不相等的正整数。

    输入格式:

    输入第一行给出一个正整数N≤30),是二叉树中结点的个数。第二行给出其中序遍历序列。第三行给出其前序遍历序列。数字间以空格分隔。

    输出格式:

    在一行中输出该树反转后的层序遍历的序列。数字间以1个空格分隔,行首尾不得有多余空格。

    输入样例:

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

    输出样例:

    4 6 1 7 5 3 2

    代码:

    #include <bits/stdc++.h>
    using namespace std;
    
    const int maxn = 1e5 + 10;
    int N;
    vector<int> pre, in;
    vector<int> level(maxn, -1);
    
    void levelorder(int inl, int inr, int root, int index) {
        if(inl > inr) return;
        int i = inl;
        while(i < inr && in[i] != pre[root]) i ++;
        level[index] = pre[root];
    
        levelorder(inl, i - 1, root + 1, index * 2 + 2);
        levelorder(i + 1, inr, root - inl + i + 1, index * 2 + 1);
    }
    
    int main() {
        scanf("%d", &N);
        pre.resize(N);
        in.resize(N);
    
        for(int i = 0; i < N; i ++)
            scanf("%d", &in[i]);
        for(int i = 0; i < N; i ++)
            scanf("%d", &pre[i]);
    
        int cnt = 0;
        levelorder(0, N - 1, 0, 0);
        for(int i = 0; i < maxn; i ++) {
            if(level[i] != -1 && cnt != N - 1) {
                printf("%d ", level[i]);
                cnt ++;
            } else if(level[i] != -1) {
                printf("%d", level[i]);
                break;
            }
        }
        return 0;
    }
    

     

    今天训练赛也是智商被按在键盘上摩擦的一天呢!

  • 相关阅读:
    avaya电话重置
    Zscaler Client Connector
    tcpdump port 514
    rsyslog和过滤规则
    syslog,rsyslog和syslog-ng
    Ubuntu 搭建Rsyslog服务器
    syslog日志的类型和级别
    springboot_springSecurity整合
    springboot_整合JDBC_Druid数据源_MyBatis
    springboot_数据增删改查
  • 原文地址:https://www.cnblogs.com/zlrrrr/p/10518980.html
Copyright © 2011-2022 走看看