-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgotree.go
More file actions
75 lines (64 loc) · 1.09 KB
/
gotree.go
File metadata and controls
75 lines (64 loc) · 1.09 KB
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
package gotree
type Tree struct {
root *Node
}
type Node struct {
Key string
Left *Node
Right *Node
}
func (v *Tree) Add(key string) {
if v.root == nil {
v.root = &Node{Key: key}
} else {
v._Add(v.root, key)
}
}
func (v *Tree) _Add(n *Node, key string) {
if n.Key > key {
if n.Right == nil {
n.Right = &Node{Key: key}
} else {
v._Add(n.Right, key)
}
} else {
if n.Left == nil {
n.Left = &Node{Key: key}
} else {
v._Add(n.Left, key)
}
}
}
func (v *Tree) InOrder(visit func(key string)) {
if v.root != nil {
v._InOrder(v.root, visit)
}
}
func (v *Tree) _InOrder(n *Node, visit func(key string)) {
if n.Left != nil {
v._InOrder(n.Left, visit)
}
visit(n.Key)
if n.Right != nil {
v._InOrder(n.Right, visit)
}
}
func (v *Tree) Search(key string) (response string) {
if v.root != nil {
response = v.search(v.root, key)
}
return
}
func (v *Tree) search(n *Node, key string) (response string) {
if n.Key == key {
return "found"
}
side := &n.Left
if n.Key > key {
side = &n.Right
}
if *side != nil {
return v.search(*side, key)
}
return
}