Question

Hello. I have written the following function to remove a value from a Binary Search Tree using re...

Hello. I have written the following function to remove a value from a Binary Search Tree using resources my professors gave and stuff I found online. The problem is I don't know how it works and I need to know how it works to finish the rest of the project.

public boolean remove(T value){
    if(value == null) return false;
    class RemoveBSTObj{
        private boolean found = false;
        private Node removeBST(Node root, T value){
            if(root == null) return root; //IF there is nothing to delete just return the root
             //Recurse down the tree to find the value
             if(value.compareTo(root.data) < 0) { //if the value passed is greater than current node, recurse to the right
                 if (root.left != null)
                     root.left = removeBST(root.left, value);
             }
             else if(value.compareTo(root.data) > 0) { //if the value passed is less than current node, recurse to the left
                 if (root.right != null)
                     root.right = removeBST(root.right, value);
             }
             else{ //Now we have found the node to be deleted
                 found = true; 
                 //If the node we have found is has only one child, we can just return that child
                 if(root.right == null) return root.left;
                 else if(root.left == null) return root.right;
                 //IF the node we ave found has two children, we have to get the inOrder predesccor, which is the maximum the left subtree, and delete it
                 root.data = findPredecessor(root);
                 root.left = removeBST(root.left, root.data);
             }
             return root;
         }
     }
     RemoveBSTObj removeBSTObj = new RemoveBSTObj();
    Node holder = removeBSTObj.removeBST(root, value);
    if(!removeBSTObj.found || holder == null) return false;
    root = holder;
    size--;
   return true;
}

//findPredecessor is used in the remove() function

public static T findPredecessor(Node t){
    if(t == null || t.left == null) return null; //return null if t is null or t(the root) has no left children, meaning t is the smallest
     return findMax(t.left); //we are looking for the largest value in the left subtree, which is just the maximum value of the left subtree
 }

//findMax is used in the findPredecessor() function

public static  T findMax(Node t){
    if(t == null) return null;
    if(t.right == null) return t.data; //if we find the maximum, return the data
    return findMax(t.right); //if no max found, continue recursing down the right
}
0 0
Add a comment Improve this question Transcribed image text
Answer #1

In a binary tree, you can have 3 cases when you find a particular node X, which need to be deleted.
1) The treenode has no children: In this case, you just remove the reference of X from X's parent and you are done, because there are no children of X, you don't need to worry about them.

2) The treenode has 1 child, either left or right but not both: In this case, You need to delete X, and X has a child Y. So You go to X's parent P, and instead of X getting attached to P, You attach Y to P on the same direction (If x was left child of P, then Y also becomes left child of P, and similar for right child).

3) The third and last case is when the node X (to be deleted) has both left and right children present.. in this case, We can not directly attach child Y1 and Y2 to parent P. We need to find the node which is just smaller than node X, which is known as predecessor. As in BST, root has more value than left subtree, and less value than right subtree.. So to find the predecessor of X, We go to left subtree of X and then keep on moving right till we can.. that way we reach to the predecessor of X.

20 8 4 12 10 14
Like in above image, if you need to delete 20, which has 2 child (8 and 22), then we need to find predecessor of 20. So we go to left subtree of 20, i.e. node 8. The from there, keep on moving right till we can.. so 8 -> 12 -> 14.. It means 14 is the predecessor of 20.

Next thing after finding predecessor is to copy the node value from predecessor to X. So we copy value 14 to node which contains 20 currently.. and then our target to delete will be predecessor node.. as predecessor node has no right child, we can call our above described algorithm which will help in deleting one child case.

I have tried to be very clear and thus used images.. let me know if something is not clear. Thanks!

Add a comment
Know the answer?
Add Answer to:
Hello. I have written the following function to remove a value from a Binary Search Tree using re...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • In C++ I need the printRange function, and the main.cpp program. Thanks. (Binary search tree) Write...

    In C++ I need the printRange function, and the main.cpp program. Thanks. (Binary search tree) Write a function printRange that takes as input a binary search tree t and two keys, k1 and k2, which are ordered so that k1 < k2, and print all elements x in the tree such that k1 <= x <= k2. You can add this function in BinarySearchTree.h (click the link) that we used in the lecture and lab 7. public: void printRange(int k1,...

  • Please I need help ASAP Java Programing: Binary Search Tree Fully implement the BST class in Listing 25.4 (on page 961 of the 11th Edition of the text). Design and write a (main) driver program to com...

    Please I need help ASAP Java Programing: Binary Search Tree Fully implement the BST class in Listing 25.4 (on page 961 of the 11th Edition of the text). Design and write a (main) driver program to completely test every method in the BST class to ensure the class meets all its requirements. You should read the Listing 25.5: TestBST.java for an idea of what your program should look like. Listing 25.4 BST.java public class BST> extends AbstractTree { protected TreeNode...

  • write a new test program called RemoveDuplicates.java. The program reads text input from keyboard or a text file and adds the words to a BST. The program then traverses the BST and prints out the word...

    write a new test program called RemoveDuplicates.java. The program reads text input from keyboard or a text file and adds the words to a BST. The program then traverses the BST and prints out the words in order (based on ASCII/UNICODE order) on the screen (or to output text file). Note that you may need to make some changes to BST.java. Sample test: ----jGRASP exec: java -ea removeDuplicates Original Text: a B 2 n w C q K l 0...

  • 1) Extend the Binary Search Tree ADT to include a public method leafCount that returns the...

    1) Extend the Binary Search Tree ADT to include a public method leafCount that returns the number of leaf nodes in the tree. 2) Extend the Binary Search Tree ADT to include a public method singleParent-Count that returns the number of nodes in the tree that have only one child. 3) The Binary search tree ADT is extended to include a boolean method similarTrees that receives references to two binary trees and determines whether the shapes of the trees are...

  • Using the following implementation of Tree class Node   {   public int iData;              // data item (key)   public...

    Using the following implementation of Tree class Node   {   public int iData;              // data item (key)   public double dData;           // data item   public Node leftChild;         // this node's left child   public Node rightChild;        // this node's right child   public void displayNode()      // display ourself      {      System.out.print('{');      System.out.print(iData);      System.out.print(", ");      System.out.print(dData);      System.out.print("} ");      }   }  // end class Node //------------------------------------------------------------------ import java.io.IOException; import java.util.Stack; public class Tree { private Node root; // first node of tree // ------------------------------------------------------------- public Tree() // constructor { root = null; }...

  • I need to do a tree sort method but the treesortMethod is not working /****Binarytree class****\...

    I need to do a tree sort method but the treesortMethod is not working /****Binarytree class****\ package Tree; public class BinaryTree { private TreeNode root; // head of the list    //constructor - create an empty binary tree public BinaryTree() { root = null;    }    //isEmpty() - return true if tree is empty, false otherwise public boolean isEmpty() { return (root == null); }    //deleteTree() - remove all items from tree public void deleteList() { root =...

  • Removing Nodes from a Binary Tree in Java This section requires you to complete the following...

    Removing Nodes from a Binary Tree in Java This section requires you to complete the following method within BinaryTree.java: public void remove(K key) { } The remove method should remove the key from the binary tree and modify the tree accordingly to maintain the Binary Search Tree Principle. If the key does not exist in the binary tree, no nodes should be removed. In case there is a non-null left child, it should take the place of the removed node....

  • BST JAVA FILE import java.util.*; public class BST <E extends Comparable <E>> {    private TreeNode<E>...

    BST JAVA FILE import java.util.*; public class BST <E extends Comparable <E>> {    private TreeNode<E> overallRoot;    public BST() {        overallRoot = null;    }    // ************ ADD ************ //    public void add(E addThis) {        if (overallRoot == null) {            overallRoot = new TreeNode<>(addThis);        } else {            add(overallRoot, addThis);        }    }    private TreeNode<E> add(TreeNode<E> node, E addThis) {        if...

  • Hi, So I have a finished class for the most part aside of the toFile method...

    Hi, So I have a finished class for the most part aside of the toFile method that takes a file absolute path +file name and writes to that file. I'd like to write everything that is in my run method also the toFile method. (They are the last two methods in the class). When I write to the file this is what I get. Instead of the desired That I get to my counsel. I am having trouble writing my...

  • write the method that return the kth smallest item in the binary search tree. for example...

    write the method that return the kth smallest item in the binary search tree. for example if the tree has 18 node and the user enter 13 then the method should return the 13 smallest element in the tree. I has a method that done it recursively but I want to Implement findKth nonrecursively public String findKth( String k ) { return findKth( k, root).data; } public Node findKth(int k, Node t ) {             if( t...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT