-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnode.go
More file actions
128 lines (104 loc) · 1.69 KB
/
Copy pathnode.go
File metadata and controls
128 lines (104 loc) · 1.69 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
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
package btree
// Node ...
type Node struct {
Key int
Value interface{}
Left *Node
Right *Node
}
func (n *Node) put(newNode *Node) {
switch {
case newNode.Key < n.Key:
if n.Left == nil {
n.Left = newNode
} else {
n.Left.put(newNode)
}
default:
if n.Right == nil {
n.Right = newNode
} else {
n.Right.put(newNode)
}
}
}
func (n *Node) find(key int) (interface{}, bool) {
if n == nil {
return "", false
}
switch {
case key < n.Key:
return n.Left.find(key)
case key > n.Key:
return n.Right.find(key)
}
return n.Value, true
}
func (n *Node) remove(key int, parent *Node) *Node {
if n == nil {
return nil
}
switch {
case key < n.Key:
return n.Left.remove(key, n)
case key > n.Key:
return n.Right.remove(key, n)
}
if n.Left == nil && n.Right == nil {
n.replace(parent, nil)
return n
}
if n.Left == nil {
n.replace(parent, n.Right)
return n
}
if n.Right == nil {
n.replace(parent, n.Left)
return n
}
replacement := n.Left.max()
n.Key = replacement.Key
n.Value = replacement.Value
return replacement.remove(replacement.Key, parent)
}
func (n *Node) replace(parent *Node, newNode *Node) {
if n == nil {
return
}
if n == parent.Left {
parent.Left = newNode
return
}
parent.Right = newNode
}
func (n *Node) smallestRightNode() *Node {
for {
if n != nil && n.Left != nil {
n = n.Left
} else {
break
}
}
return n
}
func (n *Node) max() *Node {
if n == nil {
return nil
}
if n.Right == nil {
return n
}
return n.Right.max()
}
func (n *Node) min() *Node {
if n == nil {
return nil
}
if n.Left == nil {
return n
}
return n.Left.min()
}
func (n *Node) balance(s *Node) {
// TODO: BALANCE TREE
}