# [Leet Code] Average of Levels In Binary Tree

`Input:    3   / \  9  20    /  \   15   7Output: [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].`
`# 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 = rightclass 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)`

--

--

--

Learning, and posting my findings!

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

## Matthew Boyd

Learning, and posting my findings!