The method returns false because of its recursive nature. In recursive function after finding the value, it will return the value to its parent copy of the method and that will return to its parent as per the code. We need to store the result somehow to take it to the first call of the recursive method.
In simple words, we need to store the result in a variable and return that variable as a final value from the recursive function.
For programmers, I am sharing a code to take help from and deeply understand it out.
public boolean contains (int i){
boolean result= false;
boolean flag = recursiveContains(root, i, result);
System.out.println(flag);
return flag;
}
public boolean recursiveContains(Node root, int i, boolean result)
{
// if root not null
if (root != null){
// if i value found in RandomBST
if (root.value == i) {
result = true; // result is used for understanding
return result;
}
else if (i < root.value) {
//if i smaller then root.value search i in leftchild
result = recursiveContains(root.left, i, result);
} else {
//if i>root.value search for i in rightchild
result = recursiveContains(root.right, i, result);
}
}
return result;
}
Further, I am adding a picture explanation of the code. But it requires concentration. I have called the above function for i=9. and shown how it returns true. It totally create 3 calls of contains method.
enter image description here