File tree 2 files changed +22
-16
lines changed
2 files changed +22
-16
lines changed Original file line number Diff line number Diff line change @@ -4,15 +4,18 @@ import replace_node from '../deletion/replace_node.js';
4
4
import swap_color from './swap_color.js' ;
5
5
6
6
/**
7
- * Swap pointers and colors of a node and its left child.
7
+ * Swap pointers and colors of a node and its left child B with one constraint:
8
+ * - B's right child is a leaf
9
+ *
10
+ * NOTE: This constraint is implied because B is A's in-subtree predecessor.
8
11
*
9
12
* p p
10
13
* | |
11
14
* -A -B
12
15
* / \ / \
13
16
* +B c -> +A c
14
17
* / \ / \
15
- * a b a b
18
+ * a - a -
16
19
*
17
20
* @param {Node } A - The node.
18
21
* @return {Node } The node B.
@@ -23,7 +26,7 @@ const swap_left = (A) => {
23
26
const B = A . left ;
24
27
assert ( B instanceof Node ) ;
25
28
const a = B . left ;
26
- const b = B . right ;
29
+ assert ( B . right === null ) ;
27
30
const c = A . right ;
28
31
29
32
if ( A . parent === null ) {
@@ -34,8 +37,7 @@ const swap_left = (A) => {
34
37
35
38
A . parent = B ;
36
39
37
- A . right = b ;
38
- if ( b !== null ) b . parent = A ;
40
+ A . right = null ;
39
41
B . right = c ;
40
42
if ( c !== null ) c . parent = B ;
41
43
Original file line number Diff line number Diff line change @@ -3,13 +3,19 @@ import Node from '../types/Node.js';
3
3
import swap_color from './swap_color.js' ;
4
4
5
5
/**
6
- * Swap pointers and colors of two NON-ADJACENT nodes.
6
+ * Swap pointers and colors of two NON-ADJACENT nodes with three constraints:
7
+ * - B is not the root
8
+ * - B is its parent right child
9
+ * - B's right child is a leaf
7
10
*
8
- * p q q p
9
- * | | | |
11
+ * NOTE: These three constraints are implied because B is A's in-subtree
12
+ * predecessor without being A's left child.
13
+ *
14
+ * p q q p
15
+ * | \ \ |
10
16
* -A +B +A -B
11
17
* / \ / \ / \ / \
12
- * u v x y -> x y u v
18
+ * u v x - -> x - u v
13
19
*
14
20
* @param {Node } A - The first node.
15
21
* @param {Node } B - The second node.
@@ -23,27 +29,25 @@ const swap_non_adjacent = (A, B) => {
23
29
const v = A . right ;
24
30
const q = B . parent ;
25
31
const x = B . left ;
26
- const y = B . right ;
32
+ assert ( B . right === null ) ;
33
+ assert ( q !== null ) ;
34
+ assert ( B === q . right ) ;
27
35
28
36
if ( p !== null ) {
29
37
if ( A === p . left ) p . left = B ;
30
38
else p . right = B ;
31
39
}
32
40
33
- if ( q !== null ) {
34
- if ( B === q . right ) q . right = A ;
35
- else q . left = A ;
36
- }
41
+ q . right = A ;
37
42
38
43
A . parent = q ;
39
44
A . left = x ;
40
- A . right = y ;
45
+ A . right = null ;
41
46
B . parent = p ;
42
47
B . left = u ;
43
48
B . right = v ;
44
49
45
50
if ( x !== null ) x . parent = A ;
46
- if ( y !== null ) y . parent = A ;
47
51
if ( u !== null ) u . parent = B ;
48
52
if ( v !== null ) v . parent = B ;
49
53
You can’t perform that action at this time.
0 commit comments