-
Notifications
You must be signed in to change notification settings - Fork 0
/
rbtree.go
121 lines (101 loc) · 2.05 KB
/
rbtree.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
// Package rbtree provides a red-black tree implementation.
package rbtree
const (
red = false
black = true
)
// Compare compares two values. Returns 0 if a==b, negative if a < b, and
// positive a > b.
type Compare func(a, b interface{}) int
// RedBlackTree is a red-black tree.
type RedBlackTree struct {
// Compare is used to compare values in the red-black tree for ordering.
Compare
root *node
size int
}
// New constructs an empty red-black tree.
func New(compare Compare) *RedBlackTree {
return &RedBlackTree{Compare: compare}
}
// Size returns the size of the red-black tree in constant time.
func (r *RedBlackTree) Size() int {
return r.size
}
// Max returns the maximum value in the tree.
func (r *RedBlackTree) Max() interface{} {
if r.root == nil {
return nil
}
return r.root.max().value
}
// Min returns the minimum value in the tree.
func (r *RedBlackTree) Min() interface{} {
if r.root == nil {
return nil
}
return r.root.min().value
}
type node struct {
value interface{}
left, right, parent *node
color bool
}
func (n *node) sibling() *node {
if n == n.parent.left {
return n.parent.right
}
return n.parent.left
}
func (n *node) max() *node {
for n.right != nil {
n = n.right
}
return n
}
func (n *node) min() *node {
for n.left != nil {
n = n.left
}
return n
}
func (n *node) defcolor() bool {
if n == nil {
return black
}
return n.color
}
func (r *RedBlackTree) replace(src, dest *node) {
if src.parent == nil {
r.root = dest
} else {
if src == src.parent.left {
src.parent.left = dest
} else {
src.parent.right = dest
}
}
if dest != nil {
dest.parent = src.parent
}
}
func (r *RedBlackTree) rotateLeft(src *node) {
dest := src.right
r.replace(src, dest)
src.right = dest.left
if dest.left != nil {
dest.left.parent = src
}
dest.left = src
src.parent = dest
}
func (r *RedBlackTree) rotateRight(src *node) {
dest := src.left
r.replace(src, dest)
src.left = dest.right
if dest.right != nil {
dest.right.parent = src
}
dest.right = src
src.parent = dest
}