In CLRS, the authors introduce the rotation operation in red-black tree by following pseudocode:
LEFT-ROTATE(T, x)
y = x.right # Line 1
x.right = y.left # Line 2
if y.left ≠ T.nil # Line 3
y.left.p = x # Line 4
y.p = x.p
if x.p == T.nil
T.root = y
elseif x == x.p.left
x.p.left = y
else x.p.right = y
y.left = x
x.p = y
where attribute .left, .right, .p corresponding to its left, right child, and its parent. T is the tree.
My main questions lie in Line 3 and Line 4:
Why do I need to have the if condition of Line 3? The book says that NIL is actually a leaf of the red-black tree, so I assume that NIL can also have parent pointer. These codes should still work without Line 3.
With the Line 1 and Line 2, can I write Line 4 as
x.right.p = x
? If they are actually the same, is there a reason that the author chose to write it asy.left.p = x
?
My instinct is that x.right.p = x
is different from y.left.p = x
. However, I cannot find a good explanation for this.
I've checked out the definition of pointers, but it is still quite confusing after I googled a lot...