What is the correct way to rotate two nodes (A) and (B) connected in a binary search tree to balance it?
What is the correct way to rotate two nodes (A) and (B) connected in a binary search tree to balance it?
Let's call the rotated nodes of (a) and (b). In addition, the pointer (P) is the root pointer, (Q) is the left pointer of (b), (R) is the right pointer of (a) and the precedence relation of nodes values is as follows: A <= a <= B <= b <= C
. The following image shows how the piece of the tree where it rotates (a) and (b) in both directions begins and ends.
(Temporário)=(P)
followed by (P)=(Q)
followed by (Q)=(R)
and finally (R)=(Temporário)
.
To make the rotation of the right tree to the left tree, just the opposite process, just make the new value of (P) equal to the old value of (R), the new value of (R) equals to the old value of (Q) and the new value of (Q) is equal to the old value of (P). That is, something like (Temporário)=(P)
followed by (P)=(R)
followed by (R)=(Q)
and finally (Q)=(Temporário)
.