-
Notifications
You must be signed in to change notification settings - Fork 267
/
binary_tree.rb
67 lines (46 loc) · 1.13 KB
/
binary_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
67
# frozen_string_literal: true
require "test/unit/assertions"
include Test::Unit::Assertions
class BinaryTree
attr_accessor :value
attr_writer :left, :right
def left
@left ||= BinaryTree.new
end
def right
@right ||= BinaryTree.new
end
def search(received_value)
return value if value == received_value || value.nil?
if received_value < value
left.search(received_value)
else
right.search(received_value)
end
end
def insert(received_value)
return @value = received_value if value.nil?
return left.insert(received_value) if received_value <= value
right.insert(received_value)
end
def to_a
return [] if value.nil?
left.to_a + [value] + right.to_a
end
end
tree = BinaryTree.new
tree.insert(42)
tree.insert(43)
tree.insert(44)
assert_equal(42, tree.search(42))
assert_equal(43, tree.search(43))
assert_equal(44, tree.search(44))
assert_equal(nil, tree.search(45))
tree = BinaryTree.new
assert_equal([], tree.to_a)
tree.insert(42)
assert_equal([42], tree.to_a)
tree.insert(43)
assert_equal([42, 43], tree.to_a)
tree.insert(41)
assert_equal([41, 42, 43], tree.to_a)