【问题标题】:I need help for binary search algorithm in C programming [closed]我需要 C 编程中二进制搜索算法的帮助 [关闭]
【发布时间】:2022-01-25 04:51:21
【问题描述】:
#include <stdio.h>
#include <stdlib.h>

struct node {
    int data;
    struct node *left;
    struct node *right;
};

struct node * add(struct node * root,int newData){
    if (root==NULL)
    {
        struct node * root = (struct node *)malloc(sizeof(struct node));
        root->data=newData;
        root->left=NULL;
        root->right=NULL;
        return root;
    }
    
    struct node * tmp = root;
    if (tmp->data<newData)
        tmp->right = add(tmp->right,newData);
    if (tmp->data >newData)
        tmp->left = add(tmp->left,newData);
}



void pre_order_traversal(struct node* root) {
    if (root==NULL)
        return;
    if(root != NULL) {
      printf("%d ",root->data);
      pre_order_traversal(root->left);
      pre_order_traversal(root->right);
   }
}

void inorder_traversal(struct node* root) {
    if (root==NULL)
        return;
   if(root != NULL) {
      inorder_traversal(root->left);
      printf("%d ",root->data);          
      inorder_traversal(root->right);
   }
}

void post_order_traversal(struct node* root) {
    if (root==NULL)
        return;
   if(root != NULL) {
      post_order_traversal(root->left);
      post_order_traversal(root->right);
      printf("%d ", root->data);
   }
}

int main(){
    struct node * tree1 = NULL;
    tree1 = add(tree1,5);
    tree1 = add(tree1,17);
    tree1 = add(tree1,21);
    tree1 = add(tree1,19);
    

    pre_order_traversal(tree1);
}

当我运行这段代码时,我得到了这个错误 分段错误(核心转储)

【问题讨论】:

  • 如果你得到一个核心转储,那么你应该检查它。它将提供大量有关段错误的信息。
  • 编译器警告非常清楚:warning: non-void function does not return a value in all control paths [-Wreturn-type].

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


【解决方案1】:

您需要在add末尾添加return rootreturn tmp

【讨论】:

    猜你喜欢
    • 2012-08-25
    • 2021-11-12
    • 1970-01-01
    • 1970-01-01
    • 2012-10-16
    • 1970-01-01
    • 2020-08-03
    • 1970-01-01
    • 2018-04-30
    相关资源
    最近更新 更多