I was brushing up on the concept of recursion and working with binary trees. I don‘t understand the difference between instances of using a return statement with a recursive call and other times when return is not used. I‘ll give code illustrating my question.
Here is a function that checks if a value is present in a BST:
public boolean containsNodeRecursive(Node current, int value) {
if (current == null) {
return false;
}
if (value == current.data) {
return true;
}
//HERE, THE RECURSIVE CALL IS PRECEDED BY A RETURN STATEMENT
return value < current.data
? containsNodeRecursive(current.left, value)
: containsNodeRecursive(current.right, value);
}
}
Here is a function for insertion of data into a BST:
public Node insert(Node current, int data) {
if (current == null) {
return createNode(data);
} else if (data < current.data) {
//RECURSIVE CALL HERE WITHOUT USE OF A RETURN STATEMENT
current.left = insert(current.left, data);
} else if (data > current.data) {
current.right = insert(current.right, data);
}
return current;
}
I think my question boils down to: “When should we return a recursive call and when should we not?”