Simple python solution


  • 0
    A
    class Solution(object):
        def averageOfLevels(self, root):
            """
            :type root: TreeNode
            :rtype: List[float]
            """
            self.ans = []
            def average(root, h):
                if not root:
                    return
                if len(self.ans) < h+1:
                    self.ans.append([0, 0])
                
                self.ans[h] = [self.ans[h][0]+root.val, self.ans[h][1]+1]
                average(root.left, h+1)
                average(root.right, h+1)
            
            average(root, 0)
            ans = [x[0]*1.0/x[1] for x in self.ans]
            return ans
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.