Simple Python Solution Using Levels


  • 0
    M
        def averageOfLevels(self, root):
            """
            :type root: TreeNode
            :rtype: List[float]
            """
            ret = []
            curr_level = [root]
            while any(curr_level):
                total = sum((node.val if node else 0) for node in curr_level)
                ret.append(total / float(len(curr_level)))
                tmp_level = []
                for node in curr_level:
                    if node:
                        if node.left:
                            tmp_level.append(node.left)
                        if node.right:
                            tmp_level.append(node.right)
                curr_level = tmp_level
            return ret
    

Log in to reply
 

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