-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathbinary_search_tree.rb
87 lines (77 loc) · 1.52 KB
/
binary_search_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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# This file contains the Ruby code from book of
# "Data Structures and Algorithms
# with Object-Oriented Design Patterns in Ruby"
# by Bruno R. Preiss.
#
# Copyright (c) 2004 by Bruno R. Preiss, P.Eng. All rights reserved.
class BinarySearchTree < BinaryTree
include SearchTreeMethods
def initialize(*args)
super
end
def find(obj)
return nil if empty?
diff = obj <=> @key
if diff == 0
return @key
elsif diff < 0
return @left.find(obj)
elsif diff > 0
return @right.find(obj)
end
end
def min
if empty?
return nil
elsif @left.empty?
return @key
else
return @left.min
end
end
def insert(obj)
if empty?
attachKey(obj)
else
diff = obj <=> @key
if diff == 0
raise ArgumentError
elsif diff < 0
@left.insert(obj)
elsif diff > 0
@right.insert(obj)
end
end
balance
end
def attachKey(obj)
raise StateError if not empty?
@key = obj
@left = BinarySearchTree.new
@right = BinarySearchTree.new
end
def balance
end
def withdraw(obj)
raise ArgumentError if empty?
diff = obj <=> @key
if diff == 0
if not @left.empty?
max = @left.max
@key = max
@left.withdraw(max)
elsif not @right.empty?
min = @right.min
@key = min
@right.withdraw(min)
else
detachKey
end
elsif diff < 0
@left.withdraw(obj)
elsif diff > 0
@right.withdraw(obj)
end
balance
end
end