I've search around SOF for a while and read similar post. I didn't find any of those answers satisfactory. The issue i'm having is that I want to traverse a tree until 'the root node' and a target node are the same. If the 'root' == target, I want to return true else false.
This is what I have
private boolean modifiedInorderTraversal(Node newRoot, Node target){
if(newRoot.leftPointer != null){
modifiedInorderTraversal(newRoot.leftPointer, target);
}
if(newRoot == target){
System.out.println("newRoot == target");
return true;
//return false;
}
if(newRoot.rightPointer != null){
modifiedInorderTraversal(newRoot.rightPointer, target);
}
System.out.println("before false return");
//return true;
return false;
}
You'll notice commented out are return false and return true. I was able to get the program to function properly for all test cases if I swap the returns. However, I personally don't like that solution. I added print statements to trace what issue and I'm using Netbeans as my debugger. When I run the code, it does show that it is entering
if(newRoot == target){
System.out.println("newRoot == target");
return true;
//return false;
}
I know this because my line is printed. Now, it would seem that my recursion continues despite hitting the return statement true, resulting in the false return of false. I've tried using a global variable to stop the recursion to no avail. Example of that attempt
private breakRecursion = false;
private boolean example(Node newRoot, Node target){
if(!breakRecursion){
if(blah blah){recurse}
if(newRoot == target){breakRecursion = true, return true}
if(blah blah){recurse}
return false;
}
}
Any ideas? I've read that one can use an exception the break the loop, but I thought that was messy too.
***********************UPDATE*********************
I found that this works the way I expect it to
private boolean found = false;
private boolean modifiedInorderTraversal(Node newRoot, Node target){
if(newRoot.leftPointer != null){
modifiedInorderTraversal(newRoot.leftPointer, target);
}
if(newRoot == target){
found = true;
}
if(newRoot.rightPointer != null){
modifiedInorderTraversal(newRoot.rightPointer, target);
}
return found;
}
The only issue I have with this solution is that is the runtime is O(n). The worse case should be O(n), but this solution doesn't break early and traverses all the nodes regardless if where the target is found.
Your problem is that when you return from one level in the recursive stack indicating that you found the target, you forget to use this information at the higher levels to stop the search. Try this (remove the print statements in your final product of course):
That will stop the search if the value was found in the left subtree, at the current node, or in the right subtree. If the target isn't found in any one of those, then we give up. Running the above gives: