Skip to content

559. Maximum Depth of N-ary Tree 👍

  • Time: $O(n)$
  • Space: $O(h)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
 public:
  int maxDepth(Node* root) {
    if (root == nullptr)
      return 0;

    int ans = 0;

    for (Node* child : root->children)
      ans = max(ans, maxDepth(child));

    return 1 + ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution {
  public int maxDepth(Node root) {
    if (root == null)
      return 0;

    int ans = 0;

    for (Node child : root.children)
      ans = Math.max(ans, maxDepth(child));

    return 1 + ans;
  }
}
1
2
3
4
5
6
7
class Solution:
  def maxDepth(self, root: 'Node') -> int:
    if not root:
      return 0
    if not root.children:
      return 1
    return 1 + max(self.maxDepth(child) for child in root.children)