Ruby 46ms solution - BFS with Recursion


  • 0
    S
    def get_levels(nodes)
        
        return [] if nodes.empty?
        next_level = []
        current_vals = []
        
        nodes.each do |node|
            current_vals << node.val
            next_level << node.left if node.left
            next_level << node.right if node.right
        end
        
        get_levels(next_level) << current_vals
        
    end
    
    def level_order_bottom(root)
        return [] if root.nil?
        return get_levels([root])
    end
    

Log in to reply
 

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