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;
}
}
}
Best Answer
The most general recursive formula is as follows:
Using that as a template for your code, you should have something like this:
So, cleaned up, that should look like:
This is an approximation of what your recursive function should look like. I don't know what the find function does, so I don't know if it will to what you want.
Furthermore, from your description you are trying to use two numbers in the search tree, not one. In the code you have now, you are only using one. So if you pass in, say, ({a node}, 15), you will get... something. If your find function calls searchNum({top node}, result), you will be ok, I think. But I have no idea what find does so I can't say for sure.
EDIT: It might be simpler to consolidate
find
andfindHelper
.Then just call it in
searchNum
withfind(result, root)
. That is, if you have access to root insearchNum
.