Elegant Ruby solution


  • 0
    Y

    This is a simple recursive solution to the problem in Ruby:

    def is_valid_bst(root, min=nil, max=nil)
        if !root.left && !root.right 
          # base case (leaf node)
          return false if min && root.val < min
          return false if max && root.val >= max
          true # otherwise
        else
          return false if root.left && !is_valid_bst(root.left, min, root.val)
          return false if root.right && !is_valid_bst(root.right, root.val, max)
          true # otherwise
        end
    end
    

Log in to reply
 

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