关注
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; }
}
}
查看原帖
点赞 评论
相关推荐
点赞 评论 收藏
分享

点赞 评论 收藏
分享
牛客热帖
更多
正在热议
更多
# 从顶到拉给所有面过的公司评分 #
12506次浏览 119人参与
# 机械人春招想让哪家公司来捞你? #
356813次浏览 3104人参与
# 为了求职,我做过的疯狂伪装 #
10213次浏览 162人参与
# 晒晒你的中秋福利 #
14679次浏览 91人参与
# 职场破冰,你们都聊什么? #
5699次浏览 57人参与
# 工作压力大怎么缓解 #
104692次浏览 1048人参与
# 机械人怎么评价今年的华为 #
208490次浏览 1524人参与
# 广联达求职进展汇总 #
10614次浏览 50人参与
# bilibili求职进展汇总 #
84320次浏览 777人参与
# 大家实习每天都在干啥 #
88604次浏览 517人参与
# 你面试被问到过哪些不会的问题? #
18239次浏览 716人参与
# 聊聊这家公司值得去吗 #
552829次浏览 3676人参与
# 实习要如何选择和准备? #
114408次浏览 1436人参与
# 秋招报数:你投了多少家公司? #
25960次浏览 262人参与
# 上班后和你想的一样吗? #
79086次浏览 630人参与
# 电网笔面经互助 #
46351次浏览 428人参与
# 秋招的嫡长offer #
25037次浏览 238人参与
# 你觉得早上几点上班合适? #
82242次浏览 329人参与
# 上班摸鱼,你都在干些什么? #
5908次浏览 102人参与
# 秋招OC许愿 #
345448次浏览 2521人参与