Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can somebody explain me this Binary tree transplant algorithm?

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. When TRANSPLANT replaces the subtree rooted at node u with the subtree rooted at node , node u's parent becomes node ’s parent, and u's parent ends up having as its appropriate child.

like image 831
AlanRubinoff Avatar asked Sep 05 '13 21:09

AlanRubinoff


1 Answers

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 }
like image 121
yasen Avatar answered Nov 03 '22 02:11

yasen