Skip to content

Latest commit

 

History

History
55 lines (47 loc) · 1.32 KB

File metadata and controls

55 lines (47 loc) · 1.32 KB

559. Maximum Depth of N-ary Tree

Given a n-ary tree, find its maximum depth.

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:
We should return its max depth, which is 3.

Note:

  1. The depth of the tree is at most 1000.
  2. The total number of nodes is at most 5000.

Solutions (Python)

1. DFS

"""
# Definition for a Node.
class Node:
    def __init__(self, val, children):
        self.val = val
        self.children = children
"""

class Solution:
    def maxDepth(self, root: 'Node') -> int:
        if not root:
            return 0
        if not root.children:
            return 1
        return max(map(self.maxDepth, root.children)) + 1

2. BFS

"""
# Definition for a Node.
class Node:
    def __init__(self, val, children):
        self.val = val
        self.children = children
"""

class Solution:
    def maxDepth(self, root: 'Node') -> int:
        if not root:
            return 0
        depth = 1
        nodes = [n for n in root.children]
        while nodes:
            depth += 1
            nodes = [n for node in nodes for n in node.children]
        return depth