关注
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; }
}
}
查看原帖
点赞 评论
相关推荐
03-03 21:32
上海电机学院 产品经理 点赞 评论 收藏
分享
牛客热帖
更多
正在热议
更多
# 长得好看会提高面试通过率吗? #
7247次浏览 69人参与
# 百度工作体验 #
316530次浏览 2233人参与
# 巨人网络春招 #
11710次浏览 234人参与
# 沪漂/北漂你觉得哪个更苦? #
2713次浏览 58人参与
# 离家近房租贵VS离家远但房租低,怎么选 #
17067次浏览 138人参与
# 你的实习产出是真实的还是包装的? #
4663次浏览 77人参与
# MiniMax求职进展汇总 #
26215次浏览 325人参与
# AI面会问哪些问题? #
1506次浏览 40人参与
# 从事AI岗需要掌握哪些技术栈? #
956次浏览 35人参与
# HR最不可信的一句话是__ #
1439次浏览 39人参与
# 春招至今,你的战绩如何? #
19015次浏览 176人参与
# 你做过最难的笔试是哪家公司 #
2226次浏览 30人参与
# 面试被问第一学历差时该怎么回答 #
273751次浏览 2221人参与
# 校招生月薪1W算什么水平 #
134563次浏览 456人参与
# 找AI工作可以去哪些公司? #
1061次浏览 18人参与
# AI时代,哪个岗位还有“活路” #
3682次浏览 68人参与
# XX请雇我工作 #
51192次浏览 172人参与
# 学历or实习经历,哪个更重要 #
242701次浏览 1257人参与
# 简历第一个项目做什么 #
32613次浏览 398人参与
# 不考虑薪资和职业,你最想做什么工作呢? #
153128次浏览 891人参与
# 你最满意的offer薪资是哪家公司? #
77155次浏览 377人参与
# 秋招白月光 #
733001次浏览 5450人参与
查看20道真题和解析