-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtree.go
58 lines (48 loc) · 1.06 KB
/
tree.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
package main
import "errors"
// Tree ...
type Tree struct {
Root *Node
}
// Insert will inject a new node into the binary search tree
func (t *Tree) Insert(index int64, data interface{}) error {
if t.Root == nil {
t.Root = &Node{
Index: index,
Data: data,
}
return nil
}
return t.Root.Insert(index, data)
}
// Find will recursively search it's node structure
func (t *Tree) Find(index int64) (interface{}, error) {
if t.Root == nil {
return nil, errors.New("Missing root node")
}
return t.Root.Find(index)
}
// Delete will remove an item from the binary tree
func (t *Tree) Delete(index int64) error {
if t.Root == nil {
return errors.New("Missing root node")
}
fakeParent := &Node{Right: t.Root}
err := t.Root.Delete(index, fakeParent)
if err != nil {
return err
}
if fakeParent.Right == nil {
t.Root = nil
}
return nil
}
// Traverse will go down the tree in left to right order (smallest to largest)
func (t *Tree) Traverse(n *Node, f func(*Node)) {
if n == nil {
return
}
t.Traverse(n.Left, f)
f(n)
t.Traverse(n.Right, f)
}