I have trouble understanding why the below tree rotation code works. If T2 points to y.left and y.left points to x, doesn't this make the last assignment x.right = T2 equal to x.right = x? Shouldn't the pointer point to the initial T2?
Node leftRotate(Node x) {
Node y = x.right;
Node T2 = y.left;
// Perform rotation
y.left = x;
x.right = T2;
// Update heights
x.height = max(height(x.left), height(x.right)) + 1;
y.height = max(height(y.left), height(y.right)) + 1;
// Return new root
return y;
}
This line makes
T2point to the same placey.leftpointed at the time that line was run. Ify.leftis updated to point to a different object --x, in this case -- that change is not reflected inT2.Mind you, if someone changed a property of that object, that change would be reflected. E.g. the code
then
T2.foowould reflect the change tobar. It's changes to whaty.leftis referencing that aren't reflected. This is a pretty universal thing in Java, related to the whole "references are passed by value" thing.