Fastest Solution (so far) using BFS


  • 0
    A

    '''
    import sys

    class Solution:
    def largestValues(self, root):

        if (root == None):
            return []
    
        q = [(root, 0)] # queue of tuples containing node and depth of node
        maxlist = [-sys.maxsize - 1]  # list to track max in each row
    
        while (q):
            node = q.pop(0)
            if (len(maxlist) <= node[1]):
                maxlist.append(node[0].val)
            else:
                if (maxlist[node[1]] < node[0].val):
                    maxlist[node[1]] = node[0].val
    
            if (node[0].left != None):
                q.append((node[0].left, node[1] + 1))
            if (node[0].right != None):
                q.append((node[0].right, node[1] + 1))
    
        return maxlist
    

    '''


Log in to reply
 

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