[Leet Code] Average of Levels In Binary Tree

/ \
9 20
/ \
15 7
Output: [3, 14.5, 11]
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].
# 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:
if node.right:
if values != []:




Learning, and posting my findings!

Love podcasts or audiobooks? Learn on the go with our new app.

My First Project

Local and Remote Notification (iOS)

Origins of Spice: lessons learned in smart contract development (Part I)

API Authentication Frameworks

How to Scrape IKEA Products to a File and Add Them Into Your Store — eScraper

DSLinux on a DSLite with an M3DS Real card and SuperCard SD

Calculating distances from Points to Polygon Borders in Python — A Paris Example

Understanding CSS Media Queries

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Matthew Boyd

Matthew Boyd

Learning, and posting my findings!

More from Medium

What is a Singly Linked List?

LeetCode Notes: Find All Duplicates in an Array

Identify Complete Binary Tree — Leetcode 958

How to perform range addition in O(n) time and O(1) space complexity?