Given the root of a binary tree, return <em>the average value of the nodes on each level in the form of an array</em>. Answers within <code>10<sup>-5</sup></code> of the actual answer will be accepted.
Input: root = [3,9,20,null,null,15,7]Output: [3.00000,14.50000,11.00000]Explanation: The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11.Hence return [3, 14.5, 11].
from collections import dequefrom leetcode_py import TreeNodeclass Solution: # Time: O(n) # Space: O(w) where w is the maximum width of the tree def average_of_levels(self, root: TreeNode[int] | None) -> list[float]: if root is None: return [] result: list[float] = [] queue = deque([root]) while queue: level_size = len(queue) level_sum = 0 for _ in range(level_size): node = queue.popleft() level_sum += node.val if node.left is not None: queue.append(node.left) if node.right is not None: queue.append(node.right) result.append(level_sum / level_size) return result