Python DFS + Stack and BFS + Queue Solution


  • 1
    I
    #BFS + queue
    
        def findBottomLeftValue(self, root):
            if not root:
                return
    
            max_depth = 0
            queue = [(root, 1)]
            
            while queue:
                curr, level = queue.pop(0)
                if curr:
                    if level > max_depth:
                        max_depth = level
                        ans = curr.val
                    queue.append((curr.left, level + 1))
                    queue.append((curr.right, level + 1))
            return ans
    
    #DFS + stack   
    
        def findBottomLeftValue(self, root):
            if not root:
                return
            max_depth = 0
            stack = [(root, 1)]
             
            while stack:
                curr, level = stack.pop()
                if curr:
                    if level > max_depth:
                        max_depth = level
                        ans = curr.val
                    stack.append((curr.right, level + 1))
                    stack.append((curr.left, level + 1))
            return ans
    

Log in to reply
 

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