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;
}
The best way to reason with this is to draw it out and go through it a step at a time:
At the beginning of the function we have Node x:
x
/ \
L R
/ \
l1 r1
Now we say y = R.
R
/ \
L1 R1
Node T2 = R.Left which is l2
Then the rotation:
y.left (R1.Left) = x
R
/ \
x R1
/ \
l R
/ \
l1 r1
x.right = T2 (l1)
R
/ \
x r1
/ \
l l1
A great resource I found for all things tries (albeit in C) is eternally confuzzled
Node T2 = y.left;
This line makes T2
point to the same place y.left
pointed at the time that line was run. If y.left
is updated to point to a different object -- x
, in this case -- that change is not reflected in T2
.
Mind you, if someone changed a property of that object, that change would be reflected. Eg the code
Node T2 = y.left;
y.left.foo = bar;
then T2.foo
would reflect the change to bar
. It's changes to what y.left
is referencing that aren't reflected. This is a pretty universal thing in Java, related to the whole "references are passed by value" thing.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.