dfs求树的最大层次+所有最远叶节点
import java.util.*;
public class Main {
static int N = 100010;
static int[] e = new int[N * 2];
static int[] ne = new int[N * 2];
static int[] h = new int[N];
static int idx;
static int n;
static int start;
static int level;
static int max = -1;
static List<Integer> list = new ArrayList<>();
public static void add(int a,int b) {
e[idx] = b;
ne[idx] = h[a];
h[a] = idx ++;
}
public static void dfs(int begin,int level) {
if (level == max) {
list.add(begin);
}
if (level > max) {
list.clear();
max = level;
list.add(begin);
}
for (int i = h[begin];i != -1;i = ne[i]) {
int j = e[i];
if (j != begin)
dfs(j,level+1);
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
Arrays.fill(h,-1);
for (int i = 1;i <= n;i ++) {
int x = sc.nextInt();
if (x == -1) {
start = i;
continue;
}
add(x,i);
}
dfs(start,1);
System.out.println(max);
Collections.sort(list);
int j = 1;
for (int i:list) {
if (j != list.size()) {
System.out.print(i + " ");
} else {
System.out.print(i);
}
j ++;
}
}
}