Skip to content

Commit 0fdc06a

Browse files
committed
Initial commit
0 parents  commit 0fdc06a

File tree

4 files changed

+113
-0
lines changed

4 files changed

+113
-0
lines changed

.gitignore

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
.idea
2+
.vscode
3+
.DS_Store
4+
5+
[Bb]uild
6+
[Oo]ut
7+
[Tt]arget
8+
9+
*.log
10+

README.md

Whitespace-only changes.

btree.go

+100
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
package btree
2+
3+
import (
4+
"hash/fnv"
5+
)
6+
7+
type TreeNode struct {
8+
Left *TreeNode
9+
Right *TreeNode
10+
Value int64
11+
Data []byte
12+
}
13+
14+
func hashData(b []byte) int64 {
15+
h := fnv.New64a()
16+
h.Write(b)
17+
return int64(h.Sum64())
18+
}
19+
20+
func (n *TreeNode) Insert(data []byte) {
21+
if n == nil {
22+
n = &TreeNode{Value: hashData(data), Data: data}
23+
return
24+
}
25+
26+
if n.Value > hashData(data) {
27+
if n.Left == nil {
28+
n.Left = &TreeNode{Value: hashData(data), Data: data}
29+
} else {
30+
n.Left.Insert(data)
31+
}
32+
} else {
33+
if n.Right == nil {
34+
n.Right = &TreeNode{Value: hashData(data), Data: data}
35+
} else {
36+
n.Right.Insert(data)
37+
}
38+
}
39+
}
40+
func (n *TreeNode) Search(data []byte) *TreeNode {
41+
if n == nil {
42+
return nil
43+
}
44+
45+
if hashData(data) == n.Value {
46+
return n
47+
}
48+
49+
if hashData(data) < n.Value {
50+
return n.Left.Search(data)
51+
}
52+
53+
return n.Right.Search(data)
54+
}
55+
56+
func (n *TreeNode) Delete(data []byte) *TreeNode {
57+
if n == nil {
58+
return nil
59+
}
60+
61+
if hashData(data) < n.Value {
62+
n.Left = n.Left.Delete(data)
63+
} else if hashData(data) > n.Value {
64+
n.Right = n.Right.Delete(data)
65+
} else {
66+
if n.Left == nil && n.Right == nil {
67+
return nil
68+
} else if n.Left == nil {
69+
return n.Right
70+
} else if n.Right == nil {
71+
return n.Left
72+
} else {
73+
successor := n.Right
74+
for successor.Left != nil {
75+
successor = successor.Left
76+
}
77+
n.Value = successor.Value
78+
n.Data = successor.Data
79+
n.Right = n.Right.Delete(successor.Data)
80+
}
81+
}
82+
83+
return n
84+
}
85+
86+
func (n *TreeNode) Update(data []byte, newData []byte) *TreeNode {
87+
if n == nil {
88+
return nil
89+
}
90+
91+
if hashData(data) == n.Value {
92+
n.Data = newData
93+
} else if hashData(data) < n.Value {
94+
n.Left = n.Left.Update(data, newData)
95+
} else {
96+
n.Right = n.Right.Update(data, newData)
97+
}
98+
99+
return n
100+
}

go.mod

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
module github.com/gabereiser/btree
2+
3+
go 1.19

0 commit comments

Comments
 (0)