关注
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; }
}
}
查看原帖
点赞 评论
相关推荐
牛客热帖
更多
正在热议
更多
# 设计人如何选offer #
98202次浏览 687人参与
# 找工作,行业重要还是岗位重要? #
7356次浏览 96人参与
# 五一之后,实习真的很难找吗? #
45110次浏览 320人参与
# 盲审过后你想做什么? #
12524次浏览 113人参与
# 外包能不能当跳板? #
22128次浏览 191人参与
# 领导秒批的请假话术 #
9793次浏览 74人参与
# 考研可以缓解求职焦虑吗 #
20869次浏览 247人参与
# 五一假期,你打算“躺”还是“卷”? #
28311次浏览 416人参与
# 找工作前vs找工作后的心路变化 #
7163次浏览 64人参与
# 硬件人,你被哪些公司给挂了 #
46601次浏览 722人参与
# 面试等了一周没回复,还有戏吗 #
115481次浏览 1074人参与
# 大疆的机械笔试比去年难吗 #
69584次浏览 603人参与
# 应届生薪资多少才合理? #
3079次浏览 24人参与
# 牛友们的论文几号送审 #
27200次浏览 623人参与
# 写简历别走弯路 #
714288次浏览 7850人参与
# 你喜欢工作还是上学 #
37526次浏览 411人参与
# 如果有时光机,你最想去到哪个年纪? #
43256次浏览 766人参与
# 如何缓解入职前的焦虑 #
171894次浏览 1267人参与
# 如果不工作真的会快乐吗 #
101079次浏览 866人参与
# 每人推荐一个小而美的高薪公司 #
72835次浏览 1357人参与