Leetcode 637 Solution

This article provides solution to leetcode question 637 (average-of-levels-in-binary-tree)

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