-
Notifications
You must be signed in to change notification settings - Fork 1
/
binsearch-tree-create.go
147 lines (125 loc) · 2.33 KB
/
binsearch-tree-create.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
135
136
137
138
139
140
141
142
143
144
145
146
147
package main
import (
"fmt"
"errors"
)
type Tree struct {
root *Node
}
type Node struct {
value string
data string
left *Node
right *Node
}
func (t *Tree) Insert(value, data string) error {
if t.root == nil {
t.root = &Node{
value: value,
data: data,
}
return nil
}
return t.root.Insert(value, data)
}
func (n *Node) Insert(value, data string) error {
if n == nil {
return errors.New("Nil tree")
}
switch {
case value == n.value:
return nil
case value < n.value:
if n.left == nil {
n.left = &Node{
value: value,
data: data,
}
return nil
}
return n.left.Insert(value, data)
case value > n.value:
if n.right == nil {
n.right = &Node{
value: value,
data: data,
}
return nil
}
return n.right.Insert(value, data)
}
return nil
}
func (n *Node) Find(s string) (string, bool) {
if n == nil {
return "", false
}
switch {
case s == n.value:
return n.data, true
case s < n.value:
return n.left.Find(s)
default:
return n.right.Find(s)
}
}
func (n *Node) findMax(parent *Node) (*Node, *Node) {
if n.right == nil {
return n, parent
}
return n.right.findMax(n)
}
func (n *Node) replaceNode(parent, replacement *Node) error {
if n == nil {
return errors.New("Nil node to replace")
}
if n == parent.left {
parent.left = replacement
return nil
}
parent.right = replacement
return nil
}
func (n *Node) deleteNode(s string, parent *Node) error {
if n == nil {
return errors.New("Nil node to delete")
}
switch {
case s < n.value:
n.left.deleteNode(s, n)
return nil
case s > n.value:
n.right.deleteNode(s, n)
return nil
default:
if n.left == nil && n.right == nil {
n.replaceNode(parent, nil)
return nil
}
if n.left == nil {
n.replaceNode(parent, n.right)
return nil
}
if n.right == nil {
n.replaceNode(parent, n.left)
return nil
}
replacement, replparent := n.left.findMax(n)
n.value = replacement.value
n.data = replacement.data
return replacement.deleteNode(replacement.value, replparent)
}
}
func (t *Tree) Traverse(n *Node, f func(*Node)) {
if n == nil {
return
}
f(n)
t.Traverse(n.left, f)
t.Traverse(n.right, f)
}
func main() {
t := Tree{}
fmt.Println(t.Insert("com","1"), t.Insert("google","2"), t.Insert("www","3"), t.Insert("abc","4"))
t.Traverse(t.root, func(n *Node) { fmt.Println(n.value) })
}