I found this algorithm in a textbook and I'm not sure I understand it.
TRANSPLANT(T,u,v){
1 if u.p == NIL
2 T.root = v
3 else if u == u.p.left
4 u.p.left=v
5 else u.p.right == v
6 if v != NIL
7 v.p=u.p
}
Also, what do you think is p
inside the node?
Why can't he just compare the node with the node?
Notes from textbook:
In order to move subtrees around within the binary search tree, we define a subroutine
TRANSPLANT
, which replaces one subtree as a child of its parent with another subtree. WhenTRANSPLANT
replaces the subtree rooted at nodeu
with the subtree rooted at node , nodeu
's parent becomes node ’s parent, andu
's parent ends up having as its appropriate child.
As far as I understood the code, it tries to replace the node u and its corresponding subtree with some other node v and its subtree. I assume that p stands for the parent of a node.
TRANSPLANT(T,u,v) {
1 if u.p == NIL -- if u doesn't have a parent => u is the root
2 T.root = v -- then v must replace u as the root of the tree T
3 else if u == u.p.left -- if u is a left subtree of its parent
4 u.p.left = v -- then v must replace u as the left
- -- subtree of u's parent
5 else u.p.right == v -- otherwise u is a right subtree
- -- (as the tree is binary) and v must replace
- -- u as the right subtree of u's parent
6 if v != NIL -- if v has replaced u (and thus is not NIL)
7 v.p = u.p -- v must have the same parent as u
8 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With