Try to search your question here, if you can't find : Ask Any Question Now ?

Remove Function for BST Does Not Remove Any Elements from the BST

HomeCategory: stackoverflowRemove Function for BST Does Not Remove Any Elements from the BST
john asked 2 weeks ago

I have a method that’s supposed to remove the given element from a Binary Search Tree. However it doesn’t actually remove any elements from the BST when I run the program.

I understand the idea of how this function is supposed to work: to set the root of the node with the given element to a different root, but I’m almost certain my approach to it isn’t correct. I tried just setting the node of the given element to null, but that didn’t remove anything either.

public boolean remove(int removalPoint) {

    int maxData = 0;

    if (root == null)

        return false;

    if (removalPoint == root.getData()) {

        if (getRightSubtree().root == null && getLeftSubtree().root == null)

            root = null;

        if (getRightSubtree().root != null && getLeftSubtree().root == null) {

            root = getRightSubtree().root;

            getRightSubtree().root = null;

            return false;
        }

        if (getLeftSubtree().root != null && getRightSubtree().root == null) {

            root = getLeftSubtree().root;

            getLeftSubtree().root = null;

            return false; 

        }

        if (getLeftSubtree().root != null && getRightSubtree().root != null) {

            maxData = getLeftSubtree().deleteMax();

            root.setData(maxData);

            return false;

        }

        if (removalPoint < root.getData())

            getLeftSubtree().remove(removalPoint);

        if (removalPoint > root.getData())

            getRightSubtree().remove(removalPoint);

    }

    return true;

}

public int deleteMax() {

    int maxData = 0;

    BSTNode RT = getRightSubtree().root;

    if (RT == null) {

        maxData = root.getData();

        root = getLeftSubtree().root;

    }

    else
        return getRightSubtree().deleteMax();

    return maxData;

}

The output from my test cases in the main function would look like this:

Remove 30, rc=false
        20
    19
        16
12
            9
        8
    6
            5
        4

Remove 20, rc=true
    19
        16
12
            9
        8
    6
            5
        4

Remove 4, rc=true
    19
        16
12
            9
        8
    6
        5

Remove 19, rc=true
    16
12
            9
        8
    6
        5
1 Answers
Best Answer
Jyoti answered 2 weeks ago
Your Answer

10 + 7 =

Popular Tags

WP Facebook Auto Publish Powered By : XYZScripts.com