Reputation: 17
I'm trying to implement a find method in a binary tree. The problem appears when the method needs to return a value but it seems like its not executing that statement even when have other lines in the same semicolon that executes.
public String find(Node currentNode, String value)
{
if(isEmpty())
{
return null;
}
else
{
if(currentNode.getData().compareToIgnoreCase(value) == 0)
{
System.out.println("current -> "+currentNode.getData()); //showing
return currentNode.getData(); //not executing
}
if(value.compareToIgnoreCase(currentNode.getData()) < 0)
{
find(currentNode.getLeft(), value);
}
else if(value.compareToIgnoreCase(currentNode.getData()) > 0)
{
find(currentNode.getRight(), value);
}
}
return null; //always executing
}
i expect "a" but returns null.
Upvotes: 1
Views: 426
Reputation: 3947
You have to use the data that returns your recursive call, right now you are ignoring it. Also you always return null
no matter what, here's a fixed version of the program:
public String find(TreeNode currentNode, String value) {
if (currentNode == null) {
return null;
}
if(currentNode.getData().compareToIgnoreCase(value) == 0) {
return currentNode.getData(); //not executing
}
if (currentNode.getData().compareToIgnoreCase(value) > 0) {
return find(currentNode.getLeft(), value);
} else {
return find(currentNode.getRight(), value);
}
}
Upvotes: 1
Reputation: 178293
When you execute the line
find(currentNode.getLeft(), value);
Your statement return currentNode.getData();
is executing, but you are ignoring what your recursive call has returned. (Similar for the getRight()
statement.) Then the if/else statement completes and the return null
at the bottom executes. That is why you are always getting null
.
Return whatever the recursive call returns, so that the returned value propagates back to the original call properly, e.g.:
return find(currentNode.getLeft(), value);
Upvotes: 6