题目大意
一个二叉树,如果每一个层的结点数都达到最大值,则这个二叉树就是完美二叉树。对于深度为 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;
}
}