[
tree
dfs
bfs
]
Leetcode 0559 Maximum Depth of N-ary Tree
Problem statement
https://leetcode.com/problems/maximum-depth-of-n-ary-tree/
Solution
Just traverse tree with for example dfs.
Complexity
Time complexity is O(n)
, space complexity is $(h+N)
, where h
is height of tree and N
is maximum number of children of any node.
Code
class Solution:
def maxDepth(self, root):
if not root: return 0
depth = 0
for child in root.children:
depth = max(depth, self.maxDepth(child))
return depth + 1