I'm currently working on Tree Data Structures and Recursion in Java. My Plan was to have a recursive method, which traverses the Tree and checks if any Node in the Tree has this certain value. If so, the method returns true, else the method returns false. For a better understanding I added print Statements. The Issue I have is that, the method retuns false even if a node exsits with that certain value. It only returns true, if the value matches the root value. My Method looks like this:
//Calling this method in the main function
public boolean checkForValue(int value) {
return checkForValue(value, root);
}
private boolean checkForValue(int value, TreeNode current) {
//Checking if the current value is null, if so return false
if(current == null) {
return false;
} else {
//if the current nodes value matches the value we are looking for
// it should return true
if(current.value == value) {
System.out.println("Found a Node with same value");
return true;
}
//if it wasnt the value, call the method recusrivly
//with the current.right node
else {
System.out.println("Value didnt matched the current Node");
checkForValue(value, current.right);
checkForValue(value, current.left);
return false;
}
}
}
My Main Method looks like this:
public static void main(String[] args) {
Tree tree = new Tree();
tree.add(new TreeNode(20));
tree.add(new TreeNode(30));
tree.add(new TreeNode(10));
tree.add(new TreeNode(15));
tree.add(new TreeNode(5));
tree.add(new TreeNode(40));
tree.add(new TreeNode(29));
System.out.println(tree.checkForValue(40));
}
It prints out false, although the Tree has a Node with Value of 40. My Console looks like this after running it:
After finding the Node (line 6) it should just return true and not continue (line 7). How can i make sure that I stop, if I found the value?
You are ignoring the result of your recursive calls.
Rather than doing:
checkForValue(value, current.right); // Result ignored.
checkForValue(value, current.left); // Result ignored.
return false; // Always returned.
instead do:
return checkForValue(value, current.right)
|| checkForValue(value, current.left);
This will only descend into the left branch if the right branch resulted in false.