Here's my find() method:
public boolean find(int key) {
BinTreeNode node = findHelper(key, root);
if (node == null) {
return false;
} else {
return true;
}
}
private BinTreeNode findHelper(int key, BinTreeNode node) {
if (node == null) {
return null;
}
if(key == node.item) {
return node;
}
else if(key < node.item) {
return findHelper(key,node.leftChild);
}
else {
return findHelper(key,node.rightChild);
}
}
Here's my modified code. It still doesn't work :(
public boolean searchNum(BinTreeNode node, int num) {
if(node == null) {
return false;
}
else {
int result = num - node.item;
if(find(result)) {
return true;
}
if(node.leftChild != null) {
searchNum(node.leftChild, num);
}
if(node.rightChild != null) {
searchNum(node.rightChild, num);
}
return false;
}
}
I am trying to find if a given number equals the sum of any 2 numbers in a binary search tree. I know where the error is, but I don't know how to correct it.
The folliwing lines
if(find(result)) {
return true;
}
should terminate the method because once I've got a true, that's all I need and I should return the value to the calling function. However, the recursion continues to execute finally returning the value from the last recursive call. Please help.
public boolean searchNum(BinTreeNode node, int num) {
if(node == null) {
return false;
}
else {
if(node.leftChild != null) {
searchNum(node.leftChild, num);
}
int result = num - node.item;
System.out.println(node.item);
//I have a separate find() which finds if the key is in the tree
if(find(result)) {
return true;
}
if(node.rightChild != null) {
searchNum(node.rightChild, num);
}
return false;
}
}
}