关注
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;
}
}
}
查看原帖
点赞 评论
相关推荐
点赞 评论 收藏
分享
点赞 评论 收藏
分享
04-27 14:30
辽宁大学 模拟IC设计 点赞 评论 收藏
分享
牛客热帖
更多
正在热议
更多
# 设计人如何选offer #
97952次浏览 680人参与
# 找工作,行业重要还是岗位重要? #
7028次浏览 88人参与
# 五一之后,实习真的很难找吗? #
44717次浏览 313人参与
# 盲审过后你想做什么? #
12386次浏览 110人参与
# 外包能不能当跳板? #
22063次浏览 191人参与
# 领导秒批的请假话术 #
9717次浏览 74人参与
# 考研可以缓解求职焦虑吗 #
20640次浏览 244人参与
# 五一假期,你打算“躺”还是“卷”? #
26916次浏览 407人参与
# 面试等了一周没回复,还有戏吗 #
115312次浏览 1072人参与
# 找工作前vs找工作后的心路变化 #
7140次浏览 64人参与
# 牛友们的论文几号送审 #
27168次浏览 623人参与
# 你喜欢工作还是上学 #
37399次浏览 409人参与
# 应届生薪资多少才合理? #
3061次浏览 24人参与
# 写简历别走弯路 #
714192次浏览 7850人参与
# 如果有时光机,你最想去到哪个年纪? #
43227次浏览 766人参与
# 如何缓解入职前的焦虑 #
171779次浏览 1267人参与
# 每人推荐一个小而美的高薪公司 #
72826次浏览 1357人参与
# 硬件人,你被哪些公司给挂了 #
46522次浏览 720人参与
# 如果不工作真的会快乐吗 #
101027次浏览 866人参与
# 大疆的机械笔试比去年难吗 #
69572次浏览 602人参与