# Average of Levels in Binary Tree

## Problem

Given a non-empty binary tree, return the average value of the nodes on each level in the form of an array.

{% hint style="info" %}
For example:

```
Input:
    3
   / \
  9  20
    /  \
   15   7
Output: [3, 14.5, 11]
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].
```

{% endhint %}

### Thought Process

* Have a "sum" variable to add all the numbers in the queue then divide by the queue length and append this to our results list

## Solution

```
from collections import deque
class Solution:
    def averageOfLevels(self, root: TreeNode) -> List[float]:
        if root is None:
            return []
        
        result = []
        queue = deque()
        queue.append(root)
        
        while queue:
            sums = 0
            levelSize = len(queue)
            
            for _ in range(levelSize):
                currentNode = queue.popleft()
                sums+=currentNode.val
                
                if currentNode.left:
                    queue.append(currentNode.left)
                if currentNode.right:
                    queue.append(currentNode.right)
            result.append(sums/levelSize)
        return result
        
#Time: O(n)
#Space: O(n)
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://joshualbarb.gitbook.io/leetcode-problems/tree-breadth-first-search/average-of-levels-in-binary-tree.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
