参考代码:
import java.util.*; public class Main { public static Map<Integer, List<Integer>> nodeToChildren; public static void main(String[] args) { Scanner sc = new Scanner(System.in); int N = sc.nextInt(); nodeToChildren = new HashMap<>(); for (int i = 2; i <= N; i++) { int parent = sc.nextInt(); if (!nodeToChildren.containsKey(parent)) { nodeToChildren.put(parent, new ArrayList<>()); } nodeToChildren.get(parent).add(i); } System.out.println(getMaxHeight(1)); } public static int getMaxHeight(int node) { if (!nodeToChildren.containsKey(node)) { return 0; } int max = 0; List<Integer> children = nodeToChildren.get(node); for (int child : children) { max = Math.max(max, getMaxHeight(child)); } return max + children.size(); } }
0.0分
2 人评分
C语言程序设计教程(第三版)课后习题11.3 (C语言代码)浏览:1053 |
C语言训练-立方和不等式 (C语言代码)浏览:751 |
C语言程序设计教程(第三版)课后习题9.2 (Java代码)浏览:632 |
本人酷爱递归实现很多问题,这里也是浏览:557 |
C语言程序设计教程(第三版)课后习题3.7 (C语言代码)浏览:327 |
矩阵加法 (C语言代码)浏览:1723 |
字符逆序 (C语言代码)浏览:510 |
多输入输出练习2 (C语言代码)浏览:1657 |
C语言程序设计教程(第三版)课后习题5.4 (C语言代码)浏览:468 |
简单的a+b (C语言代码)浏览:657 |