python - average of level of a tree


  • 0
    S
    # 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
                ans.append(avg)
                
                # enqueue the children of the all nodes
                # in the current level
                tmpq = []
                for node in queue:
                    if node.left:
                        tmpq.append(node.left)
                    if node.right:
                        tmpq.append(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.