python - find largest in a row


  • 1
    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 largestValues(self, root):
            """
            :type root: TreeNode
            :rtype: List[int]
            """
            if not root:
                return []
            
            queue = [root]
            length = len(queue)
            ans = []
            while length:
                # put question specific code here for BFS problems
                # get the average of the current level
                max_val = max([node.val for node in queue])
                ans.append(max_val)
                
                # 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.