关注
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-11 22:03
杭州师范大学 Web前端 点赞 评论 收藏
分享
牛客热帖
更多
正在热议
更多
# 这个offer值得去吗? #
19875次浏览 172人参与
# AI coding的好用工具分享 #
88372次浏览 567人参与
# 联宝杯大学生创新大赛,你的技术值得产业级答案 #
47586次浏览 514人参与
# 如果春招能重来,我会___ #
20823次浏览 219人参与
# 实习怎么做才有更好的产出 #
49846次浏览 456人参与
# 除了线上,还能去哪些地方投简历 #
11246次浏览 115人参与
# 在爱玛,骑向未来 #
602次浏览 62人参与
# 找工作以来,你最看不惯__ #
79351次浏览 594人参与
# 上班苦还是上学苦呢? #
345049次浏览 2069人参与
# 字节开奖 #
149790次浏览 673人参与
# 薪资爆料 #
422082次浏览 2226人参与
# 大学四年该怎么过,才不算浪费时间? #
23802次浏览 106人参与
# 你觉得实习能学到东西吗 #
154063次浏览 1494人参与
# 毕业后不工作的日子里我在做什么 #
269006次浏览 1738人参与
# 面试线索爆料 #
130891次浏览 704人参与
# AI“智障”时刻 #
40326次浏览 193人参与
# 刚工作的你,踩过哪些坑? #
46629次浏览 296人参与
# 一份好的简历长什么样? #
41863次浏览 505人参与
# 双非应该如何逆袭? #
585175次浏览 6383人参与
# 总结:offer选择,我是怎么选的 #
292826次浏览 1573人参与
# 互联网公司评价 #
537402次浏览 4193人参与
# 你知道哪些职场黑话? #
89670次浏览 480人参与
查看15道真题和解析