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; } } }
点赞 评论

相关推荐

牛客网
牛客企业服务