-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbinary_tree.rb
More file actions
43 lines (38 loc) · 986 Bytes
/
binary_tree.rb
File metadata and controls
43 lines (38 loc) · 986 Bytes
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
# A simple Binary Tree written in Ruby.
# New features could include:
# => Finding the current level for a given node
# => Finding if the tree is balanced
# => Balancing the tree
# => Displaying the tree graphically
class BinaryTree
attr_accessor :root_node
def initialize(root_node)
@root_node = root_node
end
# Start with current_node = tree.root_node
def add_node(node, current_node)
if node.value > current_node.value
if current_node.right.nil?
current_node.right = node
node.parent = current_node
else
current_node = current_node.right
add_node(node, current_node)
end
else
if current_node.left.nil?
current_node.left = node
node.parent = current_node
else
current_node = current_node.left
add_node(node, current_node)
end
end
end
end
class Node
attr_accessor :value, :parent, :left, :right
def initialize(value)
@value = value
end
end