My Python solution with 2 queues


  • 0
    D
    # 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]
            """
            q, q_next = [root], []
            curMax = - 2 ** 31
            res = []
            def processNode(node, curMax):
                q.pop(0)
                if not node:
                    return None
                if node.left:
                    q_next.append(node.left)
                if node.right:
                    q_next.append(node.right)
                return max(node.val, curMax)
            
            while q or q_next:
                while q:
                    curMax = processNode(q[0], curMax)
                if not curMax is None:
                    res.append(curMax)
                    curMax = -2 ** 31
                q, q_next = q_next, []
            
            return res
            
    

Log in to reply
 

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