每日一題20201124*(637. 二叉樹的層平均值)
阿新 • • 發佈:2020-12-05
637. 二叉樹的層平均值
思路
繼續採用廣度優先遍歷的方式,只需要稍微調整一下程式碼即可。可以參考:
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def averageOfLevels(self, root: TreeNode) -> List[float]: if root is None: return [] ans = [] queue = [root] while len(queue) > 0: size = len(queue) # 記錄這一層的總數 total = 0 for _ in range(size): current = queue.pop(0) total += current.val if current.left is not None: queue.append(current.left) if current.right is not None: queue.append(current.right) # ans陣列新增進去平均值,不用擔心size為0的問題,因為size肯定>0 # 因為queue後面的出隊和入隊已經不影響size了 ans.append(total / size) return ans