Created
July 12, 2019 03:12
-
-
Save jubishop/137a4938ecbcac003c391a3afce934a6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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