关注
import java.util.*; public class Main { private static class TreeNode { int value;
ArrayList<TreeNode> sons = new ArrayList<>(); public TreeNode(int value) { this.value = value;
}
} private static Map<Integer, TreeNode> int2TreeNode = new HashMap<>(); public static void main(String args[]) throws Exception {
Scanner cin = new Scanner(System.in); while (cin.hasNext()) { int n = cin.nextInt();
HashSet<Integer> parents = new HashSet<>();
HashSet<Integer> sons = new HashSet<>(); for (int i = 0; i < n - 1; i++) { int parent = cin.nextInt(); int son = cin.nextInt(); if (!int2TreeNode.containsKey(parent)) { int2TreeNode.put(parent, new TreeNode(parent));
} if (!int2TreeNode.containsKey(son)) { int2TreeNode.put(son, new TreeNode(son));
} int2TreeNode.get(parent).sons.add(int2TreeNode.get(son));
parents.add(parent);
sons.add(son);
}
parents.removeAll(sons); int root = 0; for (Integer item : parents) {
root = item;
}
System.out.println(dfs(root));
}
} private static int dfs(int root) {
TreeNode rootNode = int2TreeNode.get(root); if (rootNode == null || rootNode.sons.size() == 0) return 1; else { int maxx = 0; for (int i = 0, len = rootNode.sons.size(); i < len; i++) { int nextRoot = rootNode.sons.get(i).value; if (nextRoot != root) {
maxx = Math.max(maxx, dfs(nextRoot));
}
} return maxx + 1; }
}
}
查看原帖
点赞 评论
相关推荐
牛客吹哨人:哨哥晚点统一更新到黑名单:能救一个是一个!26届毁意向毁约裁员黑名单https://www.nowcoder.com/discuss/1525833
点赞 评论 收藏
分享
点赞 评论 收藏
分享
牛客热帖
更多
正在热议
更多
# 秋招开始捡漏了吗 #
16090次浏览 87人参与
# 今年秋招还有金九银十吗 #
18533次浏览 144人参与
# “vivo”个offer #
47134次浏览 311人参与
# 秋招,不懂就问 #
332723次浏览 1990人参与
# 辞职后的日常 #
15912次浏览 84人参与
# 上班后,才发现大学__白学了 #
2857次浏览 22人参与
# 满帮集团求职进展汇总 #
8306次浏览 71人参与
# 打工人的精神状态 #
101556次浏览 1312人参与
# 分享一个让你热爱工作的瞬间 #
43705次浏览 395人参与
# 上班到公司第一件事做什么? #
99093次浏览 681人参与
# 学历对求职的影响 #
550869次浏览 3904人参与
# 实习期间如何提升留用概率? #
190198次浏览 1606人参与
# 一人一个landing小技巧 #
127879次浏览 1463人参与
# 我和mentor的爱恨情仇 #
79614次浏览 434人参与
# 学历or实习经历,哪个更重要 #
192741次浏览 1026人参与
# 海信求职进展汇总 #
85298次浏览 408人参与
# 秋招结束之后的日子 #
100371次浏览 1011人参与
# 被同事甩锅了怎么办 #
25528次浏览 100人参与
# 数字马力求职进展汇总 #
212543次浏览 1680人参与
# 和mentor 1on1 都聊什么? #
4275次浏览 22人参与
# 你见过哪些工贼行为 #
32531次浏览 151人参与