-
Notifications
You must be signed in to change notification settings - Fork 1
/
check_binary_search_tree.rb
66 lines (49 loc) · 1.15 KB
/
check_binary_search_tree.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
require 'pry'
class Node
attr_accessor :value, :left, :right, :name
def initialize(options={})
@value = options[:value]
@name = options[:name]
@left = options[:left]
@right = options[:right]
end
def children?
@left && @right
end
def no_children?
@left.nil? && @right.nil?
end
def right
@right || Node.new
end
def left
@left || Node.new
end
end
def find_binary_search_tree(node, min, max)
return true if node.value == nil
if node.value > max || node.value < min
return false
end
find_binary_search_tree(node.left, min, node.value) && find_binary_search_tree(node.right, node.value, max)
end
n10 = Node.new({:value => 10})
n5 = Node.new({:value => 5})
n15 = Node.new({:value => 15})
n3 = Node.new({:value => 3})
n12 = Node.new({:value => 12})
n5.left = n3
n5.right = n12
n10.left = n5
n10.right = n15
puts find_binary_search_tree(n10, 0, 100)
n10 = Node.new({:value => 10})
n5 = Node.new({:value => 5})
n15 = Node.new({:value => 15})
n3 = Node.new({:value => 3})
n12 = Node.new({:value => 8})
n5.left = n3
n5.right = n12
n10.left = n5
n10.right = n15
puts find_binary_search_tree(n10, 0, 100)