# [Leet Code] Average of Levels In Binary Tree

Leetcode: https://leetcode.com/problems/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.

**Example 1:**

**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].

Solution:

`# Definition for a binary tree node.`

# class TreeNode(object):

# def __init__(self, val=0, left=None, right=None):

# self.val = val

# self.left = left

# self.right = right

class Solution(object):

def averageOfLevels(self, root):

"""

:type root: TreeNode

:rtype: List[float]

"""

if root:

elements = [[root.val]]

stack = [root]

self.helper(stack, elements)

answer_arr = []

for i in elements:

answer = 0.00

for j in i:

answer += j

answer_arr.append(answer / len(i))

return answer_arr

return root

def helper(self, stack, elements):

while len(stack) > 0:

values = []

length = len(stack)

for i in range(length):

node = stack.pop(0)

if node.left:

values.append(node.left.val)

stack.append(node.left)

if node.right:

values.append(node.right.val)

stack.append(node.right)

if values != []:

elements.append(values)