Ruby Solution


  • 0
    M

    Might have been overdoing it on this one, but it works.

    class TreeNode
        def leaf?
            left.nil? && right.nil?
        end
    end
    
    def find_leaves(root)
        return [] if root.nil?
        return [[root.val]] if root.leaf?
        
        queue = [root]
        leafs = []
        
        until queue.empty?
            parent = queue.shift
            
            ["left", "right"].each do |dir|
                child = parent.send(dir)
                next if child.nil?
                
                if child.left.nil? && child.right.nil?
                    leafs << child.val
                    parent.instance_variable_set("@#{dir}", nil)
                else
                    queue << child
                end
            end
        end
        
        [leafs].concat(find_leaves(root))
    end
    

Log in to reply
 

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