Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Looking for solution in unexpected results from BST implementation

I have this piece of code down below for removing a node from a BST:

private TreeNode<T> remove(T data, TreeNode<T> current) {
        if(current == null) {
            throw new InputMismatchException("The data element trying to be removed couldn't be found.");
        }
        else if(data.compareTo(current.data) < 0) {
            current.left = remove(data, current.left);
        }
        else if(data.compareTo(current.data) > 0) {
            current.right = remove(data, current.right);
        }
        else {
            if(current.right != null && current.left == null) {
                return null;
            }
            else if(current.right == null && current.left != null) {
                if(current.right != null) {
                    return current.right;
                }
                return current.left;
            }
            else {
                current.right = findSuccessor(current.right, current);
            }
        }

        size--;
        return current;
    }

it keeps on giving odd results and I can’t figure out why. Can someone please help?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

In your else statement when asserting current.right, you should be checking if it is null rather than if it isn’t.

if(current.right == null && current.left == null) {
  return null;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading