关注
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; }
}
}
查看原帖
点赞 评论
相关推荐
03-12 09:15
门头沟学院 Java
不知道怎么取名字_:其实很多mentor都很忙的,能当mentor,肯定能力强,这类人工作都是有难度的,事情多的人的 点赞 评论 收藏
分享
牛客热帖
更多
正在热议
更多
# 春招/暑实第一面是哪家? #
2731次浏览 29人参与
# 面试官最爱问的 AI 问题是...... #
1680次浏览 60人参与
# 跟HR说什么能被秒回? #
1631次浏览 29人参与
# 机械制造面试点评 #
90161次浏览 479人参与
# 如何一边实习一边找下家? #
1688次浏览 36人参与
# 你的嫡系AI是哪个? #
820次浏览 28人参与
# 你现在的工作,是“成长”还是“消耗”? #
3223次浏览 59人参与
# 找不到好工作选择GAP真的丢人吗 #
102307次浏览 1020人参与
# 现在入门AI应该走哪些方向? #
758次浏览 23人参与
# 金三银四,你的春招进行到哪个阶段了? #
19491次浏览 264人参与
# 滴滴笔试 #
37981次浏览 215人参与
# 你认为小厂实习有用吗? #
127473次浏览 702人参与
# 通信硬件公司爆料 #
200245次浏览 550人参与
# 我的岗位说明书 #
316624次浏览 2783人参与
# 你上一次加班是什么时候? #
139836次浏览 780人参与
# 美团笔试 #
708852次浏览 4690人参与
# AI岗位暴涨12倍,你会转AI赛道吗? #
7696次浏览 145人参与
# 实习进度记录 #
1218697次浏览 11852人参与
# 职场上哪些行为很加分? #
339218次浏览 3780人参与
# 小米编程考试 #
32917次浏览 156人参与