Reputation: 2758
typedef struct BinaryTreeNode {
int data;
BinaryTreeNode * left;
BinaryTreeNode * right;
} BinaryTreeNode;
int isElementInBinaryTree(BinaryTreeNode *root, int search_item) {
if(root) {
if(search_item == root -> data) return 1;
isElementInBinaryTree(root -> left, search_item);
isElementInBinaryTree(root -> right, search_item);
}
}
int main() {
BinaryTreeNode one = {1, NULL, NULL}; // root of the binary tree
BinaryTreeNode two = {2, NULL, NULL};
BinaryTreeNode three = {3, NULL, NULL};
BinaryTreeNode four = {4, NULL, NULL};
BinaryTreeNode five = {5, NULL, NULL};
BinaryTreeNode six = {6, NULL, NULL};
BinaryTreeNode seven = {7, NULL, NULL};
one.left = &two;
one.right = &three;
two.left = &four;
two.right = &five;
three.left = &six;
three.right = &seven;
printf("%d ", isElementInBinaryTree(&one, 4));
printf("\n");
return 0;
}
I am writing a function called isElementInBinaryTree that returns 1 (true) is the element exists and 0 otherwise. I don't understand why the function is always returning 0 despite the fact that the number 4 exists in the binary tree ?
Upvotes: 0
Views: 90
Reputation: 8215
Your code doesn't actually return anything when it recurses, so the 'return value' is typically whatever is left over in the register used for that purpose.
This code
if(root) {
if(search_item == root -> data) return 1;
isElementInBinaryTree(root -> left, search_item);
isElementInBinaryTree(root -> right, search_item);
}
needs to look more like this
if(root)
{
if(search_item == root -> data) return 1;
if (isElementInBinaryTree(root -> left, search_item)) return 1;
return isElementInBinaryTree(root -> right, search_item);
}
return 0;
The final return 0;
ensures you return something sensible when a NULL pointer is provided.
When you compile your code it should be displaying warnings about a typed function terminating without a return statement. You need to pay attention to those warnings and resolve them all.
The whole thing can actually be reduced to a single (though less clear) line of code
return root && ((search_item == root->data) ||
isElementInBinaryTree(root->left, search_item) ||
isElementInBinaryTree(root->right, search_item));
which relies on shortcut evaluation to only go so far as needed.
Upvotes: 3
Reputation: 780879
You're not returning anything when you perform the recursive calls. So it will only return 1
if the item is found at the root of the tree.
Also, you don't return anything when you reach the bottom of the tree without finding anyhthing, this needs to return 0
to indicate failure.
int isElementInBinaryTree(BinaryTreeNode *root, int search_item) {
if(root) {
if(search_item == root -> data) {
return 1;
}
return isElementInBinaryTree(root -> left, search_item) ||
isElementInBinaryTree(root -> right, search_item);
} else {
return 0;
}
}
Upvotes: 2