-
Notifications
You must be signed in to change notification settings - Fork 21
/
binary_tree.rb
70 lines (60 loc) · 1.4 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
68
69
70
class Node
attr_accessor :parent, :left, :right, :data
def initialize(data = nil, parent = nil, left = nil, right = nil)
@parent = parent
@left = left
@right = right
@data = data
end
end
class BinaryTree
attr_accessor :length
def insert(data)
return create_root(data) if @root.nil?
new_node = Node.new(data)
parent = @leaf_nodes.first
if parent.left.nil?
parent.left = new_node
elsif parent.right.nil?
parent.right = new_node
@leaf_nodes.shift
end
@leaf_nodes << new_node
@length += 1
end
def delete(data)
dfs.each do |node|
if node.data == data
@length -= 1
node.data = nil
end
end
end
def traverse_dfs(node = @root, &block)
yield node.data unless node.data.nil?
traverse_dfs(node.left, &block) if node.left
traverse_dfs(node.right, &block) if node.right
end
def traverse_bfs
queue = [@root]
while queue.length > 0
node = queue.shift
yield node.data if node.data
queue << node.left if node.left
queue << node.right if node.right
end
end
private
def create_root(data)
@root = Node.new(data)
@length = 1
@leaf_nodes = [@root]
end
def dfs(node = @root)
nodes = []
nodes << node unless node.data.nil?
nodes += dfs(node.left) if node.left
nodes += dfs(node.right) if node.right
nodes
end
end