演算法筆記之N叉樹的最大深度(用佇列、棧和遞迴實現)
阿新 • • 發佈:2022-05-19
給定一個 N 叉樹,找到其最大深度。
最大深度是指從根節點到最遠葉子節點的最長路徑上的節點總數。
N 叉樹輸入按層序遍歷序列化表示,每組子節點由空值分隔(請參見示例)。
示例 1:
輸入:root = [1,null,3,2,4,null,5,6]
輸出:3
解題
這個跟求二叉樹的最大深度相似,不過是子節點數變成了N。求解的時候可以參考層序遍歷用佇列實現,比較好理解。也可以用棧實現的後序遍歷,但覺得不太好理解。
- 佇列
""" # Definition for a Node. class Node: def __init__(self, val=None, children=None): self.val = val self.children = children """ import collections class Solution: def maxDepth(self, root: 'Node') -> int: if root is None: return 0 que = collections.deque() # 定義一個佇列 que.append(root) # 把根節點新增至佇列 depth = 0 while que: # 迭代處理,直到佇列為空 size = len(que) # 每次處理一層 depth += 1 # 深度+1 for i in range(size): # 處理一層的所有節點 node = que.popleft() # 取該層的一個節點 if node.children: # 把該節點的所有子節點加入佇列。所有這些子節點屬於同一層。計算完畢後進入下一個while迴圈。 for j in range(len(node.children)): que.append(node.children[j]) return depth
- 棧
這裡採用的後序遍歷。
""" # Definition for a Node. class Node: def __init__(self, val=None, children=None): self.val = val self.children = children """ import collections class Solution: def maxDepth(self, root: 'Node') -> int: stack = [] depth = 0 tmp = 0 if root: stack.append(root) while stack: node = stack.pop() if node: tmp += 1 # 當還有節點時,tmp會一直增加,直到到達最下面一層 stack.append(node) stack.append(None) if node.children: for i in range(len(node.children)): stack.append(node.children[i]) else: stack.pop() tmp -= 1 depth = max(depth,tmp) return depth
- 遞迴
class Solution: def maxDepth(self, root: 'Node') -> int: if root is None: return 0 depth = 0 for i in range(len(root.children)): depth = max(depth, self.maxDepth(root.children[i])) return depth + 1 ''' 如果是二叉樹,因為最多隻有2個子節點,可以省去for迴圈,直接返回左右子樹的最大深度即可 return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right)) '''