gpt4 book ai didi

c++ - 二叉搜索树 "contains"函数

转载 作者:搜寻专家 更新时间:2023-10-31 00:38:28 26 4
gpt4 key购买 nike

尝试为二叉树创建一个包含函数。

函数如下所示:

    bool contains(bt_node* top, int data) {
if (top == NULL) return false;
else {
if (data == top->data) return true;
else if (data < top->data) contains(top->left, data);
else if (data > top->data) contains(top->right, data);
}
}

该函数为树中实际存在的值返回 false。谁能帮忙?

谢谢,

最大

最佳答案

您忘记返回对 contains 的递归调用的值。所以你的函数的返回值是未定义的。将其更改为以下内容以使其工作:

bool contains(bt_node* top, int data) {
if (top == NULL) return false;
else {
if (data == top->data)
return true;
else if (data < top->data)
return contains(top->left, data); //you forgot to return the value
else if (data > top->data)
return contains(top->right, data);
}
}

关于c++ - 二叉搜索树 "contains"函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18090324/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com