1. 程式人生 > 實用技巧 >559. N叉樹的最大深度

559. N叉樹的最大深度

給定一個 N 叉樹,找到其最大深度。

最大深度是指從根節點到最遠葉子節點的最長路徑上的節點總數。

例如,給定一個3叉樹:

我們應返回其最大深度,3。

說明:

樹的深度不會超過1000。
樹的節點總不會超過5000。

來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/maximum-depth-of-n-ary-tree

bfs

"""
# 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 q = [root, None] d = 0 while q: node = q.pop(0) if not node: d += 1 if q: q.append(None) continue if
node and node.children: for child in node.children: q.append(child) return d