Skip to content

Commit 8b24de0

Browse files
committed
Add binary tree in Ruby
1 parent dce9bd9 commit 8b24de0

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

src/ruby/binary_tree.rb

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
# frozen_string_literal: true
2+
3+
require 'test/unit/assertions'
4+
include Test::Unit::Assertions
5+
6+
class BinaryTree
7+
attr_accessor :value
8+
attr_writer :left, :right
9+
10+
def left
11+
@left ||= BinaryTree.new
12+
end
13+
14+
def right
15+
@right ||= BinaryTree.new
16+
end
17+
18+
def search(received_value)
19+
return value if value == received_value || value.nil?
20+
21+
if received_value < value
22+
left.search(received_value)
23+
else
24+
right.search(received_value)
25+
end
26+
end
27+
28+
def insert(received_value)
29+
return @value = received_value if value.nil?
30+
return left.insert(received_value) if received_value <= value
31+
32+
right.insert(received_value)
33+
end
34+
35+
def to_a
36+
return [] if value.nil?
37+
38+
left.to_a + [value] + right.to_a
39+
end
40+
end
41+
42+
tree = BinaryTree.new
43+
44+
tree.insert(42)
45+
tree.insert(43)
46+
tree.insert(44)
47+
48+
assert_equal(42, tree.search(42))
49+
assert_equal(43, tree.search(43))
50+
assert_equal(44, tree.search(44))
51+
assert_equal(nil, tree.search(45))
52+
53+
tree = BinaryTree.new
54+
55+
assert_equal([], tree.to_a)
56+
57+
tree.insert(42)
58+
59+
assert_equal([42], tree.to_a)
60+
61+
tree.insert(43)
62+
63+
assert_equal([42, 43], tree.to_a)
64+
65+
tree.insert(41)
66+
67+
assert_equal([41, 42, 43], tree.to_a)

0 commit comments

Comments
 (0)