Simple Recursive Ruby


  • 0
    T
    # @param {TreeNode} root
    # @return {String[]}
    def binary_tree_paths(root)
        return [] if root.nil?
        @paths = []
        path_to_leaf(nil, root)
        @paths
    end
    
    def path_to_leaf(path, node)
        #puts "node: #{node.inspect}"
        path = path.nil? ? node.val.to_s : "#{path}->#{node.val.to_s}" 
        path_to_leaf(path, node.left) if node.left
        path_to_leaf(path, node.right) if node.right
        if node.left.nil? && node.right.nil?
            @paths << path 
            return
        end
    end
    

Log in to reply
 

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