Maximum depth of n-ary tree
July 14, 2022
treeProblem URL: Maximum depth of n-ary tree
We will traverse the tree with DFS and keep a counter to keep track of every level. Then we will take the maximum from all of those level and return the counter.
"""
# Definition for a Node.
class Node:
def __init__(self, val=None, children=None):
self.val = val
self.children = children
"""
class Solution:
def maxDepth(self, root: 'Node') -> int:
if not root:
return 0
maxDepth = 0
for c in root.children:
maxDepth = max(maxDepth, self.maxDepth(c))
return 1 + maxDepth
Time Complexity: O(n)
Space Complexity: O(n)