【问题标题】:insert element in a balanced search tree在平衡搜索树中插入元素
【发布时间】:2016-04-07 15:42:55
【问题描述】:

我已经编写了以下代码,用于在 BST 中插入元素。它编译没有错误,但是当我尝试运行它时,我得到分段错误。

我尝试只使用一个节点和一个 int 而不是 2 个节点来重写函数,但仍然出现分段错误。

代码:

#include <stdio.h>
#include <stdlib.h>

struct node {
  int key_value;
  struct node *left;
  struct node *right;
  struct node *parent;
  struct node *root;
};

void treeinsert( struct node *tree, struct node *z ) {
  struct node *y = NULL;
  struct node *x = tree->root;

  while( x!=NULL ) {
    y=x;
    if( z->key_value < x->key_value ) {
      x=x->left;
    } else {
      x=x->right;
    }
  }
  z->parent = y;
  if( y==NULL ) {
    tree->root = z;
  } else if(z->key_value < y->key_value) {
    y->left = z;
  } else {
    y->right = z;
  }

}

int main() {

  struct node *tree = 0;
  struct node *z = NULL;

  int s[5] = {4,2,7,1,9}, i;


  for( i=0; i<5; i++ ) {
    z->key_value = s[i];
    treeinsert(tree, z);
  }


  return 0;
}

任何人都知道为什么会出现分段错误以及我应该如何解决它?

谢谢

【问题讨论】:

    标签: c tree segmentation-fault binary-search-tree


    【解决方案1】:

    一个想法是在主函数中使用它之前不要分配z并将其声明为NULL

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-18
      相关资源
      最近更新 更多