dfs建树、完全二叉树的后序遍历转层序遍历

题目大意

一个二叉树,如果每一个层的结点数都达到最大值,则这个二叉树就是完美二叉树。对于深度为 D 的,有 N 个结点的二叉树,若其结点对应于相同深度完美二叉树的层序遍历的前 N 个结点,这样的树就是完全二叉树。

给定一棵完全二叉树的后序遍历,请你给出这棵树的层序遍历结果。

输入格式:
输入在第一行中给出正整数 N(≤30),即树中结点个数。第二行给出后序遍历序列,为 N 个不超过 100 的正整数。同一行中所有数字都以空格分隔。

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

输入样例:

8
91 71 2 34 10 15 55 18

输出样例:

18 34 55 71 2 10 15 91

因为原题上面是按照后序来输出的,就是说给我们的是后序遍历,所以我们就直接用后序建树,然后层序输出就好了。 

AC代码:
 

import javax.print.DocFlavor;
import java.io.*;
import java.math.BigInteger;
import java.util.*;

public class Main
{
    static Scanner sc = new Scanner(System.in);
    static PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
    static int N = (int)40;
    static int a[] = new int[N];
    static int b[] = new int[N];
    static int n;
    static int cnt;

    static void dfs(int u)
    {
        if(u > n)  return;
        dfs(u * 2);
        dfs(u * 2 + 1);
        b[u] = a[cnt ++];
    }

    public static void main(String[] args) throws IOException
    {
        n = rd.nextInt();
        for(int i = 0; i < n; i ++)  a[i] = rd.nextInt();

        dfs(1);
        for(int i = 1; i < n; i ++)  pw.print(b[i] + " ");
        pw.println(b[n]);
        pw.flush();
    }
}

class rd
{
    static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    static StringTokenizer tokenizer = new StringTokenizer("");

    static String nextLine() throws IOException { return reader.readLine(); }
    static String next() throws IOException
    {
        while(!tokenizer.hasMoreTokens())  tokenizer = new StringTokenizer(reader.readLine());
        return tokenizer.nextToken();
    }
    static int nextInt() throws IOException { return Integer.parseInt(next()); }
    static double nextDouble() throws IOException { return Double.parseDouble(next()); }
    static long nextLong() throws IOException { return Long.parseLong(next()); }
    static BigInteger nextBigInteger() throws IOException
    {
        BigInteger d = new BigInteger(rd.nextLine());
        return d;
    }
}

class PII
{
    int x,y;
    public PII(int x, int y)
    {
        this.x = x;
        this.y = y;
    }
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

21RGHLY

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值