BST Contains method not working properly in JAVA

I’m writing a method to see if a value exists in a BST.

 public boolean contains(int val){
        return containsHelper(val, root);
    }
    public boolean containsHelper(int val, Node root){


        if(val < root.val && root.left != null) {
            containsHelper(val, root.left);
        }
        else if(val > root.val && root.right != null) {
            containsHelper(val, root.right);
        }
        else { //theyre equal
            return true;
        }

        return false;

    }

I dont understand why my method isn’t working, its going into the else where they are equal, but still returning false.

Answer

consider adding an explicit base case. and an explicit case when you want to return true.

public boolean contains(int val){
    return containsHelper(val, root);
}
public boolean containsHelper(int val, Node root){
    if(root == null) return false;

    if(root.val == val) return true;
    else if (root.val < val) {
        return containsHelper(val, root.right);
    }else {
        return containsHelper(val, root.left);
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *