Skip to content

Commit 4263e17

Browse files
authored
Merge pull request kelvins#323 from mfornaciari/add-binary-tree-in-ruby
Add binary tree in Ruby
2 parents 495b4be + 028dd55 commit 4263e17

File tree

2 files changed

+69
-2
lines changed

2 files changed

+69
-2
lines changed

README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1718,8 +1718,8 @@ In order to achieve greater coverage and encourage more people to contribute to
17181718
</a>
17191719
</td>
17201720
<td> <!-- Ruby -->
1721-
<a href="./CONTRIBUTING.md">
1722-
<img align="center" height="25" src="./logos/github.svg" />
1721+
<a href="./src/ruby/binary_tree.rb">
1722+
<img align="center" height="25" src="./logos/ruby.svg" />
17231723
</a>
17241724
</td>
17251725
<td> <!-- JavaScript -->

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)