在BST中插入节点的问题(迭代方法)

时间:2018-04-12 07:54:26

标签: c tree binary-search-tree

下面是我在BST中插入节点的代码。 我正面临分段错误。我试图用gdb进行调试,发现在插入第二个节点时插入(& root,9)时崩溃了

current->left = newNode(key);

在if条件下循环while循环。我无法找到根本原因。请帮助我,告诉我这是什么问题。

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

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

struct Node* newNode(int item)
{
  struct Node *temp = (struct Node *)malloc(sizeof(struct Node));
  temp->data = item;
  temp->left = temp->right = NULL;
  return temp;
}


void insert(struct Node **root_ref,int key)
{
  struct Node *current;
  struct Node *parent;

  if(*root_ref == NULL)
  {
    *root_ref = newNode(key);
  }
  else
  {
    parent = *root_ref;
    while(1)
    {
      current = parent;
      if(current->data > key)
      {
        current = current->left;
        if(current == NULL)
        {
          current->left = newNode(key);
          // break;
          return;
     }
  }
  else
  {
    current = current->right;
    if(current == NULL)
    {
       current->right = newNode(key);
       //break;
       return;
    }
  }
} //End of while
}
 return;
 }

int main()
{
  struct Node *root=NULL;
  insert(&root,10);
  insert(&root,9);
  insert(&root,11);
  insert(&root,12);
  insert(&root,8);
  insert(&root,7);

  return 0;
 }

2 个答案:

答案 0 :(得分:0)

您尝试访问元素的属性,仅当元素为NULL !!

current = current->left;
if(current == NULL)
{
  current->left = newNode(key);
  // break;
  return;
}

这就是为什么你有一个段错误。

您应该测试左侧属性是否为NULL。如果是,请添加新元素,否则转到左侧。

if(current->left == NULL)
{
  current->left = newNode(key);
  return;
}
else
{
  current = current->left;
}

答案 1 :(得分:0)

这个while循环

while(1)
{
  current = parent;
  //...

没有意义,因为在循环开始时,指针current始终设置为循环中未更改的指针parent

这些if语句

    if(current == NULL)
    {
      current->left = newNode(key);
      // break;
      return;
 }

if(current == NULL)
{
   current->right = newNode(key);
   //break;
   return;
}

也没有意义,因为如果current等于NULL,那么对current->leftcurrent-->right的访问会导致未定义的行为。

该功能过于复杂,并且存在特殊情况。

该功能可以按照以下方式显示,如演示程序中所示。

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

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

struct Node * newNode( int item )
{
    struct Node *temp = ( struct Node * )malloc( sizeof( struct Node ) );

    if ( temp )
    {
        temp->data = item;
        temp->left = temp->right = NULL;
    }

    return temp;
}

int insert( struct Node **root_ref, int key )
{
    struct Node *temp = newNode( key );
    int success = temp != NULL;

    if ( success )
    {
        while ( *root_ref != NULL )
        {
            if ( key < ( *root_ref )->data ) root_ref = &( *root_ref )->left;
            else root_ref = &( *root_ref )->right;
        }

        *root_ref = temp;
    }

    return success;
}

int main(void) 
{
    struct Node *root = NULL;

    insert( &root, 10 );
    insert( &root, 9 );
    insert( &root, 11 );
    insert( &root, 12 );
    insert( &root, 8 );
    insert( &root, 7 );

    return 0;
}