c - 二叉搜索树

标签 c binary-tree 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) 的二叉搜索树。我的 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/

相关文章:

c - 如何将长度为用户输入的数组大小?

java - 如何遍历二叉树?

c++ - 我的代码是以正确的方式使用 OOPS 概念还是我让它变得不必要的复杂?

c - C中的二叉搜索树-删除具有左右子树的节点时出错

java - 如何使用 arrayList 在 Iterator 中实现 next()

c - 为什么 fwrite 向后打印十六进制值?

c - 使用动态内存分配在函数返回时中止陷阱 6

c - 在 linux 中生成鼠标、键...等事件

c - 使用数组实现二叉树

java - 计算二叉树的边总数