"""
# Definition for a Node.
class Node:
def __init__(self, val=None, children=None):
self.val = val
self.children = children
"""
# Runtime: 40 ms, faster than 90.09% of Python3 online submissions for Maximum Depth of N-ary Tree.
# Memory Usage: 15.8 MB, less than 100.00% of Python3 online submissions for Maximum Depth of N-ary Tree.
# class Solution:
# def maxDepth(self, root: 'Node') -> int:
# if not root: return 0
# if not root.children: return 1
# self.maxDepth = 1
# depth = 1
# def dfs(node, depth):
# if not node or not node.children:
# self.maxDepth = max(self.maxDepth, depth)
# depth = 0
# return
# depth += 1
# if node.children:
# for child in node.children:
# dfs(child, depth)
# dfs(root, depth)
# return self.maxDepth
class Solution:
def maxDepth(self, root: 'Node') -> int:
if not root: return 0
q = [root, None]
depth = 0
while q:
node = q.pop(0)
if node is None:
depth += 1
if q: q.append(None)
continue
if node and node.children:
for child in node.children:
q.append(child)
return depth
https://leetcode.com/problems/maximum-depth-of-n-ary-tree/submissions/