[英]Function in C always returning 0 despite true value
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;
}
我正在编写一个名为isElementInBinaryTree的函数,该函数返回1(true)是元素存在,否则返回0。 我不明白为什么尽管二进制树中存在数字4,但函数总是返回0?
您的代码在递归时实际上不返回任何内容,因此,“返回值”通常是用于该目的的寄存器中剩余的值。
这段代码
if(root) {
if(search_item == root -> data) return 1;
isElementInBinaryTree(root -> left, search_item);
isElementInBinaryTree(root -> right, search_item);
}
需要看起来像这样
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;
最终return 0;
确保在提供NULL指针时返回有意义的内容。
编译代码时,它应该显示有关类型化函数终止而没有return语句的警告。 您需要注意这些警告并予以解决。
实际上,整个过程可以简化为一行代码(尽管不太清楚)
return root && ((search_item == root->data) ||
isElementInBinaryTree(root->left, search_item) ||
isElementInBinaryTree(root->right, search_item));
它依赖于快捷方式评估,仅在需要时才执行。
执行递归调用时,您不会返回任何内容。 因此,如果在树的根目录中找到该项目,它将仅返回1
。
另外,到达树的底部时如果找不到任何内容,您将不会返回任何东西,这需要返回0
表示失败。
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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.