关注
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; }
}
}
查看原帖
点赞 评论
相关推荐
点赞 评论 收藏
分享
01-30 14:23
浙江工业大学 Java 点赞 评论 收藏
分享

点赞 评论 收藏
分享
牛客热帖
更多
正在热议
更多
# 饿了么求职进展汇总 #
21145次浏览 242人参与
# 面试常问题系列 #
21167次浏览 640人参与
# 神州信息求职汇总 #
41997次浏览 291人参与
# 牛友故事会 #
36097次浏览 722人参与
# 2025退税开始啦 #
32968次浏览 419人参与
# 蚂蚁求职进展汇总 #
26094次浏览 291人参与
# 职场中你干过哪些“蠢”事 #
92200次浏览 499人参与
# 你的秋招第一场笔试是哪家 #
62913次浏览 785人参与
# 面试时被问的最奇葩的问题 #
15554次浏览 91人参与
# 假如你的老板掉河里,你的工作能为他做什么 #
22312次浏览 349人参与
# 大学生该如何认清当下的就业环境? #
3270次浏览 18人参与
# HR问:你期望的薪资是多少?如何回答 #
8950次浏览 267人参与
# 阿里求职进展汇总 #
116922次浏览 1095人参与
# 面试官是我前女友 #
84901次浏览 632人参与
# 米哈游求职进展汇总 #
240674次浏览 1775人参与
# 汇川技术求职进展汇总 #
107808次浏览 754人参与
# 我在牛爱网找对象 #
156812次浏览 1198人参与
# 机械人,秋招第一次笔试的企业是哪家? #
26006次浏览 256人参与
# 美团求职进展汇总 #
1529289次浏览 13725人参与
# 面试中,你被问过哪些奇葩问题? #
56435次浏览 702人参与
# 通信/硬件求职避坑tips #
40258次浏览 341人参与