蓝桥杯第一题 【编程|20分】通过先序和中序数组生成后序数组

【编程|20分】通过先序和中序数组生成后序数组

时间限制:C/C++2秒,其他语言4秒
空间限制:C/C++262144K,其他语言524288K
64bit IO Format:%lld

题目描述:给出一棵二叉树的先序和中序遍历,通过这两个数组直接生成正确的后序数组。

输入描述:
第一行一个整数,表示二叉树的大小。
第二行n个整数a_i,表示二叉树的先序遍历数组。
第三行n个整数b_i,表示二叉树的中序遍历数组。

输出描述:
输出一行n个整数表示二叉树的后序遍历数组。

示例1(输入输出示例仅供调试,后台判题数据一般不包含示例)
输入:
3
1 2 3
2 1 3
输出:
2 3 1

备注:
1≤n≤10000
1≤ai,bi≤n
数据保证合法

AC代码:

#include<iostream>
#include<string.h>
#include<vector>
using namespace std;
const int N = 10010;
int z[N], h[N], x[N], n;

void dfs(int l, int zl, int zr)
{
    int rt = 0, lz = 0, rz = 0;
    for (rt = 1; rt <= n && x[l] != z[rt]; rt++);
    lz = rt - zl; rz = zr - rt;
    if (lz > 0)    dfs(l + 1, zl, rt - 1);
    if (rz > 0)    dfs(l + lz + 1, rt + 1, zr);
    printf("%d ", x[l]);
}


int main()
{
    int i;
    scanf("%d", &n);
    for (int i = 1; i <= n; i++)
        scanf("%d", &x[i]);
    for (i = 1; i <= n; i++)
        scanf("%d", &z[i]);
    dfs(1, 1, n);
    puts(" ");
    return 0;
}

在VS2019下,需要把scanf改为scanf_s:

#include<iostream>
#include<string.h>
#include<vector>
using namespace std;
const int N = 10010;
int z[N], h[N], x[N], n;

void dfs(int l, int zl, int zr)
{
    int rt = 0, lz = 0, rz = 0;
    for (rt = 1; rt <= n && x[l] != z[rt]; rt++);
    lz = rt - zl; rz = zr - rt;
    if (lz > 0)    dfs(l + 1, zl, rt - 1);
    if (rz > 0)    dfs(l + lz + 1, rt + 1, zr);
    printf("%d ", x[l]);
}


int main()
{
    int i;
    scanf_s("%d", &n);
    for (int i = 1; i <= n; i++)
        scanf_s("%d", &x[i]);
    for (i = 1; i <= n; i++)
        scanf_s("%d", &z[i]);
    dfs(1, 1, n);
    puts(" ");
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值