LeetCode Problem 559: “Maximum Depth of N-ary Tree”
Given an N-ary tree, find its maximum depth.
An N-ary tree is simply a tree in which a node can have at most N children. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
For example, given a 3-ary tree:
1
/|\
3 2 4
/ \
5 6
The maximum depth of this tree is 3.
maxDepth.root, which is the root node of the N-ary tree.0).None, return 0.1 if the node has no children.1.1 for each level.Given the recursion’s simplicity for this problem, we’ll implement the recursive DFS solution.
Here’s the implementation using the DFS approach:
# Definition for a Node.
class Node:
def __init__(self, val=None, children=None):
self.val = val
self.children = children if children is not None else []
class Solution:
def maxDepth(self, root: 'Node') -> int:
if not root:
return 0
elif not root.children:
return 1
else:
max_depth = 0
for child in root.children:
max_depth = max(max_depth, self.maxDepth(child))
return max_depth + 1
In this code:
root is None. If so, the depth is 0.1.Running the above code will correctly return the maximum depth of an N-ary tree as expected.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?