关注
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; }
}
}
查看原帖
点赞 评论
相关推荐
查看20道真题和解析 点赞 评论 收藏
分享
牛客热帖
更多
正在热议
更多
# 在大厂上班是一种什么样的体验 #
11295次浏览 142人参与
# 你的mentor是什么样的人? #
50891次浏览 716人参与
# 程序员找工作至少要刷多少题? #
19645次浏览 253人参与
# 我和mentor的爱恨情仇 #
106037次浏览 942人参与
# 论秋招对个人心气的改变 #
11849次浏览 167人参与
# 校招第一份工作你干了多久? #
136531次浏览 597人参与
# 机械人避雷的岗位/公司 #
43696次浏览 302人参与
# 设计人如何选offer #
189558次浏览 868人参与
# 为了减少AI幻觉,你注入过哪些设定? #
5159次浏览 157人参与
# 你的秋招进行到哪一步了 #
2530102次浏览 23253人参与
# 机械人还在等华为开奖吗? #
312012次浏览 1582人参与
# 牛客AI体验站 #
7108次浏览 194人参与
# 重来一次,我还会选择这个专业吗 #
411106次浏览 3898人参与
# 我现在比当时_,你想录用我吗 #
9014次浏览 115人参与
# 12306一秒售罄,你抢到回家的票了吗? #
2122次浏览 48人参与
# 一张图晒一下你的AI员工 #
5369次浏览 120人参与
# AI Coding的使用心得 #
4866次浏览 103人参与
# 刚入职的你踩过哪些坑 #
7162次浏览 130人参与
# 关于春招/暑期实习,你想知道哪些信息? #
7834次浏览 121人参与
# 应届生进小公司有什么影响吗 #
118373次浏览 1159人参与
