Skip to content

Instantly share code, notes, and snippets.

@jubishop
Created July 12, 2019 03:12
Show Gist options
  • Save jubishop/137a4938ecbcac003c391a3afce934a6 to your computer and use it in GitHub Desktop.
Save jubishop/137a4938ecbcac003c391a3afce934a6 to your computer and use it in GitHub Desktop.
require_relative 'jubilib/binary_tree'
def validate_and_return_minmax(node)
left_valid, left_min, left_max = node.left.nil? ?
[true, node.val, node.val] :
validate_and_return_minmax(node.left)
return [false, 0, 0] unless left_valid
right_valid, right_min, right_max = node.right.nil? ?
[true, node.val, node.val] :
validate_and_return_minmax(node.right)
return [false, 0, 0] unless right_valid
valid = ((node.left.nil? or left_max < node.val) and (node.right.nil? or right_min > node.val))
return [false, 0, 0] unless valid
return [true, left_min, right_max]
end
def is_valid_bst(root)
return true if root.nil?
valid, min, max = validate_and_return_minmax(root)
return valid
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment