@@ -6,8 +6,23 @@ function llrb(compare) {
6
6
return new LLRBTree ( compare ) ;
7
7
}
8
8
9
+
10
+ function Node ( key , value , red , left , right ) {
11
+ this . key = key ;
12
+ this . value = value ;
13
+ this . red = red ;
14
+ this . left = left ;
15
+ this . right = right ;
16
+ }
17
+
18
+ var bottom = new Node ( null , null , false ) ;
19
+ bottom . left = bottom ;
20
+ bottom . right = bottom ;
21
+
22
+
9
23
function LLRBTree ( compare ) {
10
24
this . compare = compare || defaultCompare ;
25
+ this . root = bottom ;
11
26
}
12
27
13
28
LLRBTree . prototype = {
@@ -16,7 +31,7 @@ LLRBTree.prototype = {
16
31
var n = this . root ,
17
32
cmp = this . compare ;
18
33
19
- while ( n ) {
34
+ while ( n !== bottom ) {
20
35
var c = cmp ( key , n . key ) ;
21
36
if ( c === 0 ) return n ;
22
37
n = c < 0 ? n . left : n . right ;
@@ -30,26 +45,18 @@ LLRBTree.prototype = {
30
45
}
31
46
} ;
32
47
33
- function Node ( key , value , red ) {
34
- this . key = key ;
35
- this . value = value ;
36
- this . red = red ;
37
- this . left = null ;
38
- this . right = null ;
39
- }
40
-
41
48
function insert ( h , key , value , compare ) {
42
- if ( ! h ) return new Node ( key , value , true ) ;
49
+ if ( h === bottom ) return new Node ( key , value , true , bottom , bottom ) ;
43
50
44
51
var c = compare ( key , h . key ) ;
45
52
46
53
if ( c < 0 ) h . left = insert ( h . left , key , value , compare ) ;
47
54
else if ( c > 0 ) h . right = insert ( h . right , key , value , compare ) ;
48
55
else h . value = value ;
49
56
50
- if ( isRed ( h . right ) && ! isRed ( h . left ) ) h = rotateLeft ( h ) ;
51
- if ( isRed ( h . left ) && isRed ( h . left . left ) ) h = rotateRight ( h ) ;
52
- if ( isRed ( h . left ) && isRed ( h . right ) ) flipColors ( h ) ;
57
+ if ( h . right . red && ! h . left . red ) h = rotateLeft ( h ) ;
58
+ if ( h . left . red && h . left . left . red ) h = rotateRight ( h ) ;
59
+ if ( h . left . red && h . right . red ) flipColors ( h ) ;
53
60
54
61
return h ;
55
62
}
@@ -58,10 +65,6 @@ function defaultCompare(a, b) {
58
65
return a < b ? - 1 : a > b ? 1 : 0 ;
59
66
}
60
67
61
- function isRed ( h ) {
62
- return h && h . red ;
63
- }
64
-
65
68
function rotateRight ( h ) {
66
69
var x = h . left ;
67
70
h . left = x . right ;
0 commit comments