关注
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;
}
}
}
查看原帖
点赞 评论
牛客热帖
更多
正在热议
更多
# 牛客新年AI问运 #
10861次浏览 148人参与
# 第一次面试 #
1072753次浏览 13736人参与
# 牛客AI体验站 #
17232次浏览 297人参与
# 投递几十家公司,到现在0offer,大家都一样吗 #
329196次浏览 2127人参与
# 你喜欢工作还是上学 #
89939次浏览 888人参与
# 被AI治愈的瞬间 #
91154次浏览 690人参与
# 有必要和同事成为好朋友吗? #
1872次浏览 34人参与
# 虾皮求职进展汇总 #
378396次浏览 2795人参与
# 百度求职进展汇总 #
667766次浏览 6293人参与
# 招聘要求与实际实习内容不符怎么办 #
169575次浏览 926人参与
# 如果不上班,你会去做什么 #
29500次浏览 466人参与
# 非技术岗薪资爆料 #
491497次浏览 3047人参与
# 你找工作的时候用AI吗? #
173846次浏览 893人参与
# 产品薪资爆料 #
159016次浏览 855人参与
# 你觉得什么岗位会被AI替代 #
41758次浏览 283人参与
# 考研失败就一定是坏事吗? #
222603次浏览 1543人参与
# 国企vs私企,你更想去? #
320190次浏览 2530人参与
# 我的求职精神状态 #
431957次浏览 3082人参与
# 秋招想进国企该如何准备 #
127611次浏览 620人参与
# 卷__卷不过你们,只能卷__了 #
42397次浏览 669人参与
