Java doesn't pass arguments by reference, they are passed by value. Read more here
Let's clarify by an example. Make the key you are looking for be integer with value 21
.
The situation at the beginning of the function is the following:

So now, when you say:
foundNode = node; // this doesn't reflect outside of the method
You are changing the value of foundNode
locally inside the findGivenNode()
method, it doesn't apply to outside this method. Basically, the local variable called foundNode
references the node you want to change and then you make this local variable foundNode
reference the new node by the statement above.
This change is reflected only inside the function. As soon as your function is finished, local variables don't exist anymore so neither does this local version of foundNode
. Visual result:

The simple solution is to use a Wrapper function
To keep track of the reference, you can make a simple wrapper class that will store the reference you want:
private class NodeWrapper {
Node foundNode;
NodeWrapper() {
foundNode = null;
}
}
Then you can create a new NodeWrapper
and pass that into your function instead of foundNode
NodeWrapper wrapper = new NodeWrapper();
findGivenNode(root, wrapper, key, parentStack);
Then inside your function instead of:
foundNode = node;
You say:
wrapper.foundNode = node;
This way you can maintain the reference throughout the recursion inside the NodeWrapper
. Meaning:
NodeWrapper wrapper = new NodeWrapper();
findGivenNode(root, wrapper, key, parentStack);
// at this point, wrapper.foundNode will hold the reference to the node you need
// or null if the node wasn't found
On another note, above the method you have this function prototype:
findGivenNode(root, key, foundNode, parentStack);
Seems like someone is still used to C/C++ :)
This is unnecessary in Java, you can read this question thread for reasoning behind that or just Google it.