|
|
|
Example 1: if the deletion node is a left child of its parent node
|
Example 2: if the deletion node is a right child of its parent node
|
Special situation: the deletion node is the root node
|
// p points to the node that you want to remove if ( p.left == null && p.right == null ) // Case 0: p has no subtrees { /* ======================================================= Special case: p is the root node If the root has no subtrees, then it's the ONLY node ! Removing the last node will result in an EMPTY tree ! ======================================================== */ if ( p == root ) { root = null; return; } parent = myParent; // myParent was set by findNode(x).... /* -------------------------------- Delete p from p's parent -------------------------------- */ if ( parent.left == p ) parent.left = null; else parent.right = null; return; } |
|
Example 1: if the deletion node only has a left subtree
|
Example 2: if the deletion node only has a right subtree
|
Special situation: the deletion node is the root node
|
// p points to the node that you want to remove /* ================================================== Case 1a: p has a right subtree ================================================== */ if ( p.left == null ) // If true, p has a right subtree { /* ======================================== Handle special situation: p is the root ========================================= */ if ( p == root ) { root = root.right; // After root is deleted, BST = right tree of root return; } parent = myParent; // myParent was set by findNode(x).... /* ---------------------------------------------- Link p's RIGHT subtree to the parent node ---------------------------------------------- */ if ( parent.left == p ) { // Hang p's RIGHT tree to parent.left parent.left = p.right; // Link p's right subtree to parent left } else { // Hang p's RIGHT tree to parent.right parent.right = p.right; // Link p's right subtree to parent right } return; } /* ================================================== We must do the same when p has a LEFT subtree Case 1b: p has a left subtree ================================================== */ if ( p.right == null ) // If true, p has a left child { if ( p == root ) { root = root.left; return; } parent = myParent; // myParent was set by findNode(x).... /* ---------------------------------------------- Link p's left child as p's parent child ---------------------------------------------- */ if ( parent.left == p ) parent.left = p.left; else parent.right = p.left; return; } |