题目

类型:深度优先搜索
image.png

解题思路

从 root 的所有子节点中的取最大深度,并在此基础上加一(统计 root 节点)即是答案。

代码

  1. class Solution {
  2. public int maxDepth(Node root) {
  3. if (root == null) return 0;
  4. int ans = 0;
  5. for (Node node : root.children) {
  6. ans = Math.max(ans, maxDepth(node));
  7. }
  8. return ans + 1;
  9. }
  10. }