关注
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; }
}
}
查看原帖
点赞 评论
相关推荐
查看5道真题和解析 点赞 评论 收藏
分享
点赞 评论 收藏
分享
牛客热帖
更多
正在热议
更多
# 26届春招投递记录 #
29927次浏览 217人参与
# 妈妈治愈了你哪些脆皮时刻 #
46971次浏览 347人参与
# 27届实习投递记录 #
109293次浏览 1076人参与
# 我的工作日记 #
207278次浏览 1819人参与
# 我的求职总结 #
509272次浏览 7058人参与
# 要毕业了,再不说就来不及了 #
4443次浏览 80人参与
# 大学生该如何认清当下的就业环境? #
178198次浏览 939人参与
# 我与AI的日常 #
10036次浏览 150人参与
# AI面会问哪些问题? #
132555次浏览 3301人参与
# 摸鱼被leader发现了怎么办 #
207030次浏览 937人参与
# 腾讯工作体验 #
645642次浏览 3911人参与
# 如果公司降薪,你会跳槽吗? #
168461次浏览 968人参与
# 牛友的志愿填报指南 #
72172次浏览 503人参与
# 材料专业就业可以去哪些企业岗位 #
69054次浏览 396人参与
# 你遇到过哪些神仙同事 #
147219次浏览 778人参与
# 滴!实习打卡 #
860584次浏览 6900人参与
# 面试被问期望薪资时该如何回答 #
406186次浏览 2221人参与
# 不考虑薪资和职业,你最想做什么工作呢? #
168524次浏览 913人参与
# 你在职场上见过哪些“水货”同事 #
41584次浏览 175人参与
# 今年秋招哪家公司给的薪资最良心? #
488066次浏览 2600人参与
