-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathBinary Search Tree.rb
59 lines (51 loc) · 971 Bytes
/
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
class Node
attr_accessor :left, :right, :data
def initialize(data)
@left = nil
@right = nil
@data = data
end
end
def search(root, data)
if root == nil
print "Not Found"
end
if root.data == data
print "Found At ", root.object_id
return root
end
if root.data < data
return search(root.right, data)
else
return search(root.left, data)
end
end
def insert(root, node)
if root == nil
root = node
else
if root.data < node.data
if root.right == nil
root.right = node
else
insert(root.right, node)
end
else
if root.left == nil
root.left = node
else
insert(root.left, node)
end
end
end
end
root = Node.new(50)
insert(root, Node.new(30))
insert(root, Node.new(20))
insert(root, Node.new(40))
insert(root, Node.new(10))
insert(root, Node.new(70))
insert(root, Node.new(90))
insert(root, Node.new(60))
insert(root, Node.new(80))
search(root, 90)