关注
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;
}
}
}
查看原帖
点赞 评论
相关推荐
牛客热帖
更多
- 1... 🌟择难路,未有疑,四非学院本运气拉满,春招拿下大厂后端5.8W
- 2... 其实主包早就找到工作了,但还是每天都刷7903
- 3... 史上最细SQL实战系列:sql笔试例题总结篇(建议收藏)7321
- 4... 恋爱四年没想到过自己会出轨6222
- 5... 快star-x二面凉经3979
- 6... 小红书二面(第二天oc)3552
- 7... 离开软件测试才发现外面没有雨3420
- 8... 从天坑文科到大二腾讯的经历3297
- 9... 字节拒绝、百度毁约,7.1 腾讯 Offer 到手:25 届双非碎碎念(25届最晚Offer)3132
- 10... 25届毕业现在在家呆了一个多月,没工作3077
正在热议
更多
# 计算机有哪些岗位值得去? #
2895次浏览 31人参与
# 社会教会你的第一课 #
9009次浏览 131人参与
# 现代汽车前瞻技术研发急速编程挑战赛 #
42229次浏览 293人参与
# 实习生的蛐蛐区 #
13197次浏览 114人参与
# 神州信息工作体验 #
13766次浏览 64人参与
# 应届生,你找到工作了吗 #
9807次浏览 90人参与
# 被AI治愈的瞬间 #
57436次浏览 620人参与
# 说说你知道的学历厂 #
7928次浏览 66人参与
# 你认为小厂实习有用吗? #
3534次浏览 42人参与
# 你找工作的时候用AI吗? #
3261次浏览 33人参与
# 哪一瞬间觉得自己长大了 #
1964次浏览 38人参与
# 歌尔求职进展汇总 #
55857次浏览 335人参与
# 面试尴尬现场 #
5892次浏览 43人参与
# 下班后的时间你怎么安排 #
1714次浏览 25人参与
# 简历当中有水分算不算造假? #
11378次浏览 116人参与
# 双非应该如何逆袭? #
180990次浏览 3152人参与
# 秋招盘点:机械人值得去的企业 #
74026次浏览 671人参与
# 毕业旅行去哪玩儿 #
10405次浏览 130人参与
# 三一集团提前批进度交流 #
24467次浏览 139人参与
# 秋招想进国企该如何准备 #
72057次浏览 416人参与
# 没有合适的工作,你会先找个干着,还是考公考研 #
118244次浏览 1134人参与