【发布时间】:2019-04-09 12:58:20
【问题描述】:
编写一个函数,如果给定的二叉搜索树包含给定的值,则在所用时间方面有效地返回 1,否则返回 0。
例如,对于以下树:
- n1(值:1,左:null,右:null)
- n2(值:2,左:n1,右:n3)
- n3(值:3,左:null,右:null)
调用 contains(&n2, 3) 应该返回 1,因为根在 n2 的树包含数字 3。
该函数应该返回 1,然而,它返回 0 或什么都不返回。
#include <stdlib.h>
#include <stdio.h>
typedef struct Node
{
int value;
struct Node *left;
struct Node *right;
} Node;
int contains(const Node *root, int value)
{
if (root->value == value)
return 1;
else if (value < root->value)
{
if (root->left == NULL)
return 0;
return contains(root->left, value);
}
else if (value > root->value)
{
if (root->right == NULL)
return 0;
return contains(root->left, value);
}
}
int main()
{
Node n1 = {.value=1, .left=NULL, .right=NULL};
Node n3 = {.value=3, .left=NULL, .right=NULL};
Node n2 = {.value=2, .left=&n1, .right=&n3};
printf("%d", contains(&n2, 3));
}
【问题讨论】:
-
在第二个 else if 语句中,您再次检查 root->left。那应该是 contains(root->right, value)。
-
有效!愚蠢的错误!
标签: c pointers struct binary-search-tree function-pointers