gpt4 book ai didi

c - 二叉搜索树

转载 作者:太空宇宙 更新时间:2023-11-04 06:19:32 25 4
gpt4 key购买 nike

所以我用 C 编写了一个二叉搜索树,它看起来是这样的结构:

struct tnode {
int content;
struct tnode *left; /* left tree part */
struct tnode *right; /* right tree part */
};

我的主要方法:

int main() {

struct tnode *Baum = NULL;
struct tnode *tmpPos = NULL;
Baum = addelement (Baum, 32);
Baum = addelement(Baum, 50);
Baum = addelement(Baum, 60);
tmpPos = searchnode(Baum,50);
}

所以基本上这为我创建了一个包含 3 个元素 (32,50,60) 的二叉搜索树。我的 searchnode 方法应该将指针移动到“50”,这样我就可以在之后删除它。但是,如果我正在搜索的元素是我的二叉搜索树的根,我的 searchnode 方法只会返回指针。

搜索节点:

struct tnode *searchnode(struct tnode *p, int nodtodelete) {
if (p == NULL) {
printf("Baum ist leer oder Element nicht vorhanden \n");
}

if ( p -> content == nodtodelete) {
return p;
}

if (p->content > nodtodelete) {
searchnode (p->right, p->content);
}
if (p->content < nodtodelete) {
searchnode(p->left, p->content);
}
}

也许你们可以帮助我。

最佳答案

你的函数有未定义的行为,因为它在递归调用中没有任何 return 语句。

此外,需要修复递归调用以使用正确的输入。

struct tnode *searchnode(struct tnode *p, int nodtodelete)
{
if (p == NULL)
{
printf("Baum ist leer oder Element nicht vorhanden \n");
return NULL;
}

if ( p -> content == nodtodelete)
{
return p;
}

// This is copied from OP's question but it seems suspect.
// It should probably be:
// if (p->content < nodtodelete)
if (p->content > nodtodelete)
{
return searchnode (p->right, nodtodelete);
}

return searchnode(p->left, nodtodelete);
}

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

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