python - average of level of a tree

  • 0
    # Definition for a binary tree node.
    # class TreeNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    class Solution(object):
        def averageOfLevels(self, root):
            :type root: TreeNode
            :rtype: List[float]
            queue = [root]
            length = len(queue)
            ans = []
            while length:
                # put question specific code here for BFS problems
                # get the average of the current level
                values = [1.0*node.val for node in queue]
                avg = sum(values)/length
                # enqueue the children of the all nodes
                # in the current level
                tmpq = []
                for node in queue:
                    if node.left:
                    if node.right:
                # reassign the queue
                queue = tmpq
                length = len(queue)
            return ans

Log in to reply

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