Skip to content

Commit e398503

Browse files
committed
add binary tree
1 parent 6ca20b3 commit e398503

File tree

1 file changed

+85
-0
lines changed

1 file changed

+85
-0
lines changed

trees/binary_tree.rb

+85
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
2+
class BinaryTree
3+
class Node
4+
def initialize value, parent, comparator
5+
@value = value
6+
@parent = parent
7+
@left = nil
8+
@right = nil
9+
@cmp = comparator
10+
end
11+
attr_accessor :value
12+
13+
##
14+
# Add a value to the tree, below this node.
15+
# Returns the new node.
16+
def add value
17+
if @cmp.call(@value, value) < 0
18+
if @left
19+
@left.add value, cmp
20+
else
21+
@left = Node.new value, self, @cmp
22+
end
23+
else
24+
if @right
25+
@right.add value
26+
else
27+
@right = Node.new value, self, @cmp
28+
end
29+
end
30+
end
31+
32+
##
33+
# Recursively yield left/this/right value.
34+
def each &block
35+
return enum_for(:each) unless block_given?
36+
@left.each(&block) if @left
37+
yield @value
38+
@right.each(&block) if @right
39+
nil
40+
end
41+
end
42+
43+
include Enumerable
44+
45+
##
46+
# Create a new self-sorting binary tree.
47+
#
48+
# If called with a block, it is used as the comparison function
49+
# for sorting values. By default values are compared using the
50+
# spaceship operator <=>
51+
#
52+
# @yield |a, b| => {-1, 0, 1}
53+
#
54+
def initialize &comparator
55+
comparator = lambda {|a, b| a <=> b } if !comparator
56+
@cmp = comparator
57+
@root = nil
58+
@length = 0
59+
end
60+
attr_reader :length
61+
62+
##
63+
# Add a new value to the tree.
64+
def add value
65+
if !@root
66+
@root = Node.new value, nil, @cmp
67+
@length = 1
68+
else
69+
@root.add value
70+
@length += 1
71+
end
72+
value
73+
end
74+
75+
##
76+
# Iterator over each element in the tree, in order.
77+
#
78+
# @yield |value|
79+
def each &block
80+
return enum_for(:each) unless block_given?
81+
return if !@root
82+
@root.each &block
83+
end
84+
end
85+

0 commit comments

Comments
 (0)