[英]Binary Search Tree
所以我用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)的Binary搜索树。 我的searchnode方法应该将指针移到“ 50”,以便以后可以删除它。 但是,如果我正在搜索的元素是我的二进制搜索树的根,则我的searchnode方法仅返回指针。
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);
}
}
也许你们可以帮我。
您应该传递要搜索的值,而不是节点的值:
searchnode (p->right, nodtodelete);
^
对其他递归调用进行相同的更改。
searchnode(p->left, nodtodelete);
您的函数具有未定义的行为,因为在递归调用中没有任何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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.