Search code examples
javabinary-search-tree

JAVA BST return node instance of BST node?


I'm doing a BST project which is search a value in the BST and return if it was found. I used a test method to check the codes, and it work fine. Problem came from the return type I guessed.

public BSTNode contains(BSTNode root, String needle) {
     BSTNode current = root;
     while (current != null) {
         if (current.getData().compareTo(needle) > 0)
            current=current.getLeft();
        else if (current.getData().compareTo(needle) < 0)
            current=current.getRight();
        else if (current.getData().compareTo(needle) == 0)
            return current;
        else current=null;
    }
    return current;
}

result:

BSTNode node = bst.contains(root, "delta");
    Assertions.assertTrue(node instanceof BSTNode);

false;

BSTNode node = bst.contains(root, "delta");
    Assertions.assertTrue(true);

true;

As my understanding, I believe the codes work fine and the value return was right. I just don't understand the "node instance of BSTNode" why it was false and how can I fix it?

Thank you in advanced

enter image description here


Solution

  • Your method, as written, can only ever return null. You only exit the while loop when current is null, and then you return current. null instanceof Anything is always false.

    The line current=current; will also cause an infinite loop if the value is found.

    Both of these can be addressed at once: you should return current when the comparison is 0.