-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbalance.go
80 lines (60 loc) · 1.48 KB
/
balance.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
package avltree
import (
"cmp"
)
func balanceOf[K cmp.Ordered, V any](node *Node[K, V]) int {
if node == nil {
return 0
}
return heightOf(node.Left) - heightOf(node.Right)
}
func heightOf[K cmp.Ordered, V any](node *Node[K, V]) int {
if node == nil {
return -1
}
return node.Height
}
func balance[K cmp.Ordered, V any](node *Node[K, V], threshold int) *Node[K, V] {
nodeBalance := balanceOf(node)
if nodeBalance > threshold {
// Left heavy node.
if balanceOf(node.Left) >= 0 {
node = rotateRight(node)
} else {
node = rotateLeftRight(node)
}
return node
}
if nodeBalance < -threshold {
if balanceOf(node.Right) <= 0 {
node = rotateLeft(node)
} else {
node = rotateRightLeft(node)
}
}
return node
}
func rotateLeft[K cmp.Ordered, V any](x *Node[K, V]) *Node[K, V] {
y := x.Right
x.Right = y.Left
y.Left = x
x.Height = 1 + max(heightOf(x.Left), heightOf(x.Right))
y.Height = 1 + max(heightOf(y.Left), heightOf(y.Right))
return y
}
func rotateRight[K cmp.Ordered, V any](x *Node[K, V]) *Node[K, V] {
y := x.Left
x.Left = y.Right
y.Right = x
x.Height = 1 + max(heightOf(x.Left), heightOf(x.Right))
y.Height = 1 + max(heightOf(y.Left), heightOf(y.Right))
return y
}
func rotateLeftRight[K cmp.Ordered, V any](node *Node[K, V]) *Node[K, V] {
node.Left = rotateLeft(node.Left)
return rotateRight(node)
}
func rotateRightLeft[K cmp.Ordered, V any](node *Node[K, V]) *Node[K, V] {
node.Right = rotateRight(node.Right)
return rotateLeft(node)
}