Naive Ruby Solution - Time O(n) and Space O(n) - Any suggestions?


  • 0
    M
    def level_order_bottom(root)
        return [] unless root
    
        levels = [[root]]
    
        while true
            new_level = []
            prev_level = levels.last
            prev_level.each do |node|
                new_level << node.left if node.left
                new_level << node.right if node.right
            end
            break if new_level.empty?
            levels << new_level
        end
        
        # not sure if this last part is O(n) time
        levels.map{ |level| level.map(&:val) }.reverse
    end
    

Log in to reply
 

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