-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtree.go
71 lines (63 loc) · 1.15 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
59
60
61
62
63
64
65
66
67
68
69
70
71
package binarytree
import "os"
// BinaryTree ...
type BinaryTree struct {
Root *BinaryNode
activateSplay bool
}
// NewBinaryTree ...
func NewBinaryTree() *BinaryTree {
return &BinaryTree{Root: nil, activateSplay: false}
}
// ToggleSplay toggle to use splay or not
func (t *BinaryTree) ToggleSplay(activate bool) {
t.activateSplay = activate
}
// Insert add node to the tree
func (t *BinaryTree) Insert(key float64, data interface{}) *BinaryTree {
if t.Root == nil {
t.Root = NewBinaryNode(key, data)
} else {
t.Root.Insert(key, data)
if t.activateSplay {
t.splay(key)
}
}
return t
}
// Max returns the max value node
func (t *BinaryTree) Max() *BinaryNode {
n := t.Root
if n == nil {
return nil
}
for {
if n.Right == nil {
if t.activateSplay {
t.splay(n.Key)
}
return n
}
n = n.Right
}
}
// Min returns the min value node
func (t *BinaryTree) Min() *BinaryNode {
n := t.Root
if n == nil {
return nil
}
for {
if n.Left == nil {
if t.activateSplay {
t.splay(n.Key)
}
return n
}
n = n.Left
}
}
// Print displays tree from root
func (t *BinaryTree) Print() {
t.Root.Print(os.Stdout, 0, 'M')
}