【问题标题】:Inserting a node in a binary search tree在二叉搜索树中插入一个节点
【发布时间】:2021-03-11 18:19:34
【问题描述】:

这是我声明的代码,似乎插入函数有问题,我不明白。对于初学者来说,这肯定会令人沮丧。所以,这是我全局声明的结构节点指针,

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

这是我全局声明的根节点,

struct node *root=NULL;

这是我声明的插入函数

int insert(struct node* p, struct node *newnode){
    if(p==NULL){
        p=newnode;
        p->left=NULL;
        p->right=NULL;
    }
    else{
        if(newnode->data<p->data){
            insert(p->left, newnode);
        }
        else if(newnode->data>p->data){
            insert(p->right, newnode);
        }
    }
    return 0;
}

这就是我在 main() 中调用插入函数的方式

struct node *newnode;
while(1){
  switch(n){
    case 1:
      newnode=(struct node*)malloc(sizeof(struct node));
      printf("Enter the element: ");
      scanf("%d", &newnode->data);
      insert(root, newnode);
    default:
      return 0;
  }
}

在这里我没有发现我的代码有任何问题,但我在插入函数中不断收到分段错误(代码转储)。谁能告诉我这段代码有什么错误?

【问题讨论】:

  • 您应该为循环中的每个新条目分配一个新节点。
  • @Tarik 但它应该至少不会在第一次迭代中转储
  • 如果 p 为 null,则将 newnode 设为 null。
  • 你是对的,这只是一个评论。
  • 您可以使用 >= 代替 >

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


【解决方案1】:

建议代码:

int insert(struct node* p, int value){
    if (p==NULL) {
        p = (struct node*)malloc(sizeof(struct node));
        p->data = value;
        p->left=NULL;
        p->right=NULL;
    }
    else if(value < p->data)
            p->left = insert(p->left, value); // p->left will only be modified if it is null, otherwise it will stay as is
    else if(value >= p->data)
            p->right = insert(p->right, value); // p->right will only be modified if it is null, otherwise it will stay as is
             
    return p;
}

【讨论】:

  • 我也对代码中 switch 的情况 1 做了一点改动。即 root=insert(root, value) 我得到了想要的输出,但我现在很困惑,它是如何工作的?现在 root 不会指向顶部节点,它会指向最新的节点,不是吗??
  • root 始终指向顶部节点。仅在第一次插入时,顶部节点将从 null 更改为指向新节点的指针。之后,根节点的左指针或右指针都会被修改。
  • 添加了对令人困惑的部分的评论。如果仍然不清楚,请与我联系,或将问题标记为已回答。注意:可能还有其他方法可以完成任务。我处理二叉树已经 30 多年了,当时我在 80 年代的 CS 中做 BsC。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多