There are many mistakes in your code.
As you showed in your stacktrace, the infinite recursion is in the getData
method and not in the getNodeValue
method, so you need to post the source code of the getData
method.
But the getNodeValue
method has many bugs as well.
Your first two if statements have exactly the same condition:
if (node.getData().equalsIgnoreCase(symbol)) {
and
else if (((String) node.getData()).equalsIgnoreCase(symbol)) {
the returns inside these if statements append an empty string to the result of getData()
, which already returns String
. Replace each of them with:
return node.getData();
are just a different way of writing the same, since getData() already returns a String so casting to String again doesn't make a difference.
Your next to if statements recursively call getNodeValue on leftChild
and rightChild
, but they never return anything, so you always end up returning null
in your code once you're past the first two identical if statements in your method.
You code should probably read:
if (node.getLeftChild() != null) {
String found = getNodeValue(node.getLeftChild(), symbol);
if (found != null) {
return found;
}
}
if (node.getRightChild() != null) {
String found = getNodeValue(node.getRightChild(), symbol);
if (found != null) {
return found;
}
}