-
有一棵树,输出某一深度的所有节点,有则输出这些节点,无则输出EMPTY。该树是完全二叉树。
-
输入有多组数据。
每组输入一个n(1<=n<=1000),然后将树中的这n个节点依次输入,再输入一个d代表深度。 -
输出该树中第d层得所有节点,节点间用空格隔开,最后一个节点后没有空格。
-
4 1 2 3 4 2
-
2 3
-
题目描述:
-
输入:
-
输出:
-
样例输入:
-
样例输出:
import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.ArrayList;
class Main
{
public static final boolean DEBUG = false;
public static int[] a;
public static int n, depth;
public static ArrayList<Integer> ans = new ArrayList<Integer>();
public static void dfs(int cur, int dep)
{
if (dep == depth) {
ans.add(a[cur]);
return;
}
if (cur * 2 + 1 < n) dfs(cur * 2 + 1, dep + 1);
if (cur * 2 + 2 < n) dfs(cur * 2 + 2, dep + 1);
}
public static void main(String[] args) throws IOException
{
Scanner cin;
if (DEBUG) {
cin = new Scanner(new FileReader("d:\\OJ\\uva_in.txt"));
} else {
cin = new Scanner(new InputStreamReader(System.in));
}
while (cin.hasNext()) {
n = cin.nextInt();
a = new int[n];
for (int i = 0; i < n; i++) a[i] = cin.nextInt();
depth = cin.nextInt();
ans.clear();
dfs(0, 1);
for (int i = 0; i < ans.size(); i++) {
if (i != 0) System.out.print(" ");
System.out.print(ans.get(i));
}
System.out.println();
}
}
}