Ruby Solution


  • 1
    M
    def binary_tree_paths(root)
        return [] if root.nil?
        
        root_node = [root, [root.val]]
        paths = []
        queue = [root_node]
        
        until queue.empty?
            parent, path = queue.shift
            
            if parent.left.nil? && parent.right.nil?
                paths << path.join("->")
            else
                queue << [ parent.left,  path + [parent.left.val]  ]  if parent.left
                queue << [ parent.right, path + [parent.right.val] ]  if parent.right
            end
        end
    
        paths
    end
    

Log in to reply
 

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