LeetCode Solutions

559. Maximum Depth of N-ary Tree

Time: $O(n)$

Space: $O(h)$

			

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;
  }
};
			

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;
  }
}
			

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)