【问题标题】:Debug Binary Search Tree in C在 C 中调试二叉搜索树
【发布时间】:2021-03-09 14:10:48
【问题描述】:

我试图在 C 中创建一个 BST。我只是添加了一些基本功能。但是,我似乎遇到了添加节点或按顺序遍历的问题 - 不知何故创建了一个无限循环。请提供反馈,因为我正在努力改进。谢谢!

#include <stdio.h>
#include <stdlib.h>
//node structure 
struct node{
  int data;
  struct node* left;
  struct node* right;
}typedef node;
//create node
node * createLeaf(int x){
    node * temp = (node*)malloc(sizeof(node));
    temp->data = x;
    temp->left = NULL;
    temp->right = NULL;
    return temp;
}
//insert node
node *insert(node *root,int x){
    if(root == NULL){
        root = createLeaf(x);
        return root;
    }
    else{
        if(x > root->data){
          root->right = insert(root->right,x);  
       }
        else if(x < root->data){
          root->left = insert(root->left,x);  
       }
    }
    return root;
}
//in-order traversal
void inorder(node * root){
    while(root!=NULL){
        inorder(root->left);
        printf("%d\n",root->data);
        inorder(root->right);
    }
}
int main()
{
    node * root = NULL;
    root = insert(root,5);
    insert(root,8);
    insert(root,1);
    inorder(root);
    printf("Hello World");

    return 0;
}


【问题讨论】:

  • 您的insert 缺少案例处理x == root-&gt;data。并不是说它是 问题。
  • 你为什么要用 C++ 标记一个关于 C 的问题?
  • 您的inorder 中不需要while 循环。仅递归就足以完成完整遍历。这就是无限循环的所在——root 永远不会在那里更新。将while 替换为if
  • @EugeneSh.Thanks !!

标签: c algorithm data-structures binary-search-tree


【解决方案1】:

@Eugene 建议用 if 替换 while 将解决问题 或者您可以在 while 循环的末尾添加一个中断,它也应该可以解决您的问题。 但我建议只使用递归或迭代。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 2021-10-01
    • 2011-01-31
    • 1970-01-01
    相关资源
    最近更新 更多