-
Notifications
You must be signed in to change notification settings - Fork 0
/
binary_search_tree.v
146 lines (137 loc) · 2.48 KB
/
binary_search_tree.v
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
// Binary Search Tree example by @SleepyRoy
struct Empty {}
struct Node[T] {
value T
left Tree[T]
right Tree[T]
}
type Tree[T] = Empty | Node[T]
// return size(number of nodes) of BST
fn (tree Tree[T]) size[T]() int {
return match tree {
Empty { 0 }
Node[T] { 1 + tree.left.size() + tree.right.size() }
}
}
// insert a value to BST
fn (tree Tree[T]) insert[T](x T) Tree[T] {
return match tree {
Empty {
Node[T]{x, tree, tree}
}
Node[T] {
if x == tree.value {
tree
} else if x < tree.value {
Node[T]{
...tree
left: tree.left.insert(x)
}
} else {
Node[T]{
...tree
right: tree.right.insert(x)
}
}
}
}
}
// whether able to find a value in BST
fn (tree Tree[T]) search[T](x T) bool {
return match tree {
Empty {
false
}
Node[T] {
if x == tree.value {
true
} else if x < tree.value {
tree.left.search(x)
} else {
tree.right.search(x)
}
}
}
}
// find the minimal value of a BST
fn (tree Tree[T]) min[T]() T {
return match tree {
Empty {
T(1e9)
}
Node[T] {
if tree.value < tree.left.min() {
tree.value
} else {
tree.left.min()
}
}
}
}
// delete a value in BST (if nonexistent do nothing)
fn (tree Tree[T]) delete[T](x T) Tree[T] {
return match tree {
Empty {
tree
}
Node[T] {
if tree.left !is Empty && tree.right !is Empty {
if x < tree.value {
Node[T]{
...tree
left: tree.left.delete(x)
}
} else if x > tree.value {
Node[T]{
...tree
right: tree.right.delete(x)
}
} else {
Node[T]{
...tree
value: tree.right.min()
right: tree.right.delete(tree.right.min())
}
}
} else if tree.left !is Empty {
if x == tree.value {
tree.left
} else {
Node[T]{
...tree
left: tree.left.delete(x)
}
}
} else {
if x == tree.value {
tree.right
} else {
Node[T]{
...tree
right: tree.right.delete(x)
}
}
}
}
}
}
fn main() {
mut tree := Tree[f64](Empty{})
vals := [0.2, 0.0, 0.5, 0.3, 0.6, 0.8, 0.9, 1.0, 0.1, 0.4, 0.7]
for i in vals {
tree = tree.insert(i)
}
println('[1] after insertion tree size is ${tree.size()}') // 11
del_vals := [-0.3, 0.0, 0.3, 0.6, 1.0, 1.5]
for i in del_vals {
tree = tree.delete(i)
}
print('[2] after deletion tree size is ${tree.size()}, ') // 7
print('and these elements were deleted: ') // 0.0 0.3 0.6 1.0
for i in vals {
if !tree.search(i) {
print('${i} ')
}
}
println('')
}