【Leetcode_總結】637. 二叉樹的層平均值 - python
阿新 • • 發佈:2019-01-11
Q:
給定一個非空二叉樹, 返回一個由每層節點平均值組成的陣列.
示例 1:
輸入: 3 / \ 9 20 / \ 15 7 輸出: [3, 14.5, 11] 解釋: 第0層的平均值是 3, 第1層是 14.5, 第2層是 11. 因此返回 [3, 14.5, 11].
連結:https://leetcode-cn.com/problems/average-of-levels-in-binary-tree/description/
思路:同 二叉樹的層次遍歷 將輸出取平均值即可
程式碼:
class Solution: def averageOfLevels(self, root): """ :type root: TreeNode :rtype: List[float] """ res = [] que = [root] if root == None: return res while que: tempList = [] for i in range(len(que)): node = que.pop(0) tempList.append(node.val) if node.left: que.append(node.left) if node.right: que.append(node.right) res.append(sum(tempList)/len(tempList)) return res