关注
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;
}
}
}
查看原帖
点赞 评论
相关推荐
点赞 评论 收藏
分享

点赞 评论 收藏
分享

点赞 评论 收藏
分享
牛客热帖
更多
正在热议
更多
# 为了求职,我做过的疯狂伪装 #
8141次浏览 113人参与
# 从顶到拉给所有面过的公司评分 #
5220次浏览 64人参与
# 职场破冰,你们都聊什么? #
4145次浏览 53人参与
# 晒晒你的中秋福利 #
13874次浏览 83人参与
# 聊聊这家公司值得去吗 #
547713次浏览 3657人参与
# 广联达求职进展汇总 #
9961次浏览 50人参与
# 产品每日一题 #
59985次浏览 604人参与
# 实习要如何选择和准备? #
113742次浏览 1435人参与
# 机械人,你最希望上岸的公司是? #
181159次浏览 1894人参与
# 你面试被问到过哪些不会的问题? #
15282次浏览 641人参与
# 机械笔面试考察这些知识点 #
9668次浏览 89人参与
# 如何快速融入团队? #
31435次浏览 278人参与
# bilibili求职进展汇总 #
80641次浏览 748人参与
# 浪潮求职进展汇总 #
15818次浏览 131人参与
# 你觉得早上几点上班合适? #
81622次浏览 329人参与
# 上班后和你想的一样吗? #
78404次浏览 628人参与
# 工作压力大怎么缓解 #
103972次浏览 1043人参与
# 远景求职进展汇总 #
60628次浏览 317人参与
# 电网笔面经互助 #
45722次浏览 428人参与
# 秋招报数:你投了多少家公司? #
22367次浏览 231人参与