-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
134 lines (121 loc) · 2.08 KB
/
main.go
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
package main
import (
"fmt"
"sync"
)
var T int // minimum order
type node struct {
keys []int
children []*node
isLeaf bool
}
type BTree struct {
root *node
mu sync.Mutex
}
func NewNode() *node {
return &node{
keys: make([]int, 0),
isLeaf: true,
children: make([]*node, 0),
}
}
func NewBTree(val ...int) *BTree {
if len(val) == 0 {
val = append(val, 10)
}
T = val[0]
return &BTree{
root: NewNode(),
}
}
func (t *BTree) Insert(val int) error {
if t == nil {
err := fmt.Errorf("empty tree")
return err
}
t.mu.Lock()
defer t.mu.Unlock()
insert(val, t)
return nil
}
func (t *BTree) PrintTree() error {
if t == nil {
err := fmt.Errorf("empty tree")
return err
}
t.mu.Lock()
defer t.mu.Unlock()
printTree(t.root)
fmt.Println("")
return nil
}
func (t *BTree) Search(val int) (bool, error) {
if t == nil {
err := fmt.Errorf("empty tree")
return false, err
}
t.mu.Lock()
defer t.mu.Unlock()
foundNode := search(t.root, val)
exists := false
if foundNode != nil {
fmt.Println("Found", val)
exists = true
} else {
fmt.Println("Does not exist", val)
}
return exists, nil
}
func (t *BTree) Delete(key int) error {
if t.root == nil {
err := fmt.Errorf("empty tree")
return err
}
t.mu.Lock()
defer t.mu.Unlock()
if !t.root.isLeaf && len(t.root.keys) == 0 {
// If the root has no keys and is not a leaf, set the root to its only child.
t.root = t.root.children[0]
}
deleteNode(&t.root, key)
return nil
}
func (t *BTree) Update(oldVal int, newVal int) error {
var err error
if t == nil {
err = fmt.Errorf("empty tree")
return err
}
n := search(t.root, oldVal)
if n == nil {
err = fmt.Errorf("old key not in tree")
return err
}
// delete oldVal and insert newVal
err = t.Delete(oldVal)
if err != nil {
return err
}
err = t.Insert(newVal)
if err != nil {
return err
}
return nil
}
func main() {
fmt.Println("B-Tree Example")
t := NewBTree()
t.Insert(5)
t.Insert(8)
t.Insert(10)
t.Insert(12)
t.Insert(14)
t.Insert(4)
t.Insert(6)
t.Search(10)
t.Update(10, 13)
t.PrintTree()
// benchmark(t)
// concurrency(t)
}