Created
September 29, 2023 21:26
-
-
Save jlcarrascof/ec58e9ae193a74718af2dfdffa8add6b to your computer and use it in GitHub Desktop.
Algo & DS - Binary Search Tree operations challenge
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
class Node | |
attr_reader :data | |
attr_accessor :left, :right | |
def initialize data | |
@data = data | |
end | |
end | |
def array_to_tree(array, index = 0) | |
# use your function from the previous challenge | |
if index >= array.length || array[index] == 0 | |
return nil | |
end | |
node = Node.new(array[index]) | |
node.left = array_to_tree(array, 2*index+1) | |
node.right = array_to_tree(array, 2*index+2) | |
return node | |
end | |
def search_tree_helper(node, min = nil, max = nil) | |
return true if node.nil? | |
return false if min != nil && node.data <= min | |
return false if max != nil && node.data >= max | |
search_tree_helper(node.left, min, node.data) && search_tree_helper(node.right, node.data, max) | |
end | |
def search_tree?(array) | |
root = array_to_tree(array) | |
# write your code here | |
return search_tree_helper(root) | |
end | |
puts search_tree?([10, 4, 12]) | |
# => true | |
puts search_tree?([10, 5, 7]) | |
# => false |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment