Leetcode 637 Solution
This article provides solution to leetcode question 637 (average-of-levels-in-binary-tree)
Access this page by simply typing in "lcs 637" in your browser address bar if you have bunnylol configured.
Leetcode Question Link
https://leetcode.com/problems/average-of-levels-in-binary-tree
Solution
# 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 []
q = [root]
ans = []
while q:
s = len(q)
sum_v = 0
for i in range(s):
node = q.pop(0)
sum_v += node.val
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
ans.append(sum_v / s)
return ans