2014-11-27 2 views
1

Я начинаю перемещаться в двоичные деревья в моем классе C. Я понимаю концепцию двоичного дерева, но теперь я пытаюсь получить более глубокое понимание того, как это работает. Я попытался создать простое двоичное дерево, которое меняет размер на основе того, что вводит пользователь. Всякий раз, когда я запускаю программу, он сбрасывается после первого ввода. Может ли кто-нибудь помочь мне понять, почему?Дробление двоичного дерева в C

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

typedef struct node 
{ 
    int value; 
    struct node *left; 
    struct node *right; 
}node; 

void traverse(node *root); 
void addnode (node *root, int nUser); 
int checknode (node *root, int nUser); 

int main (void) 
{ 
    int nUser; 
    node *root; 
    root=(node *)malloc(sizeof(node)); 
    root->value=10; 
    do 
    { 
     printf("Please enter any integer, enter 0 when done\n\n\n"); /*Program crashes when I enter the first value, unsure why*/ 
     scanf("%d",&nUser); 
     if(!(checknode(root,nUser)))/*check node runs through the binary tree to find the data if it exists, returns 1 if exists, 0 if it doesn't*/ 
      addnode(root,nUser); /*add node runs through the binary tree, when it finds a place where the number will fit, that is a null pointer where the number can be placed it will create a new node with the value and null pointers on right and left*/ 
    }while(nUser); 
    traverse(root);/*should traverse the tree and print out values*/ 
    return(0); 
} 

void traverse(node *root) 
{ 
    printf("%d/n",root->value); 
    if(root->left) 
     { 
     traverse(root->left); 
     } 
    if(root->right) 
     { 
     traverse(root->right); 
     } 
} 

void addnode (node *root, int nUser) 
{ 
if(root->value<nUser) 
    if(root->right) 
     { 
     addnode(root->right,nUser); 
     } 
    else 
     { 
     node *temp; 
     temp=(node *)malloc(sizeof(node)); 
     temp->value=nUser; 
     root->right=temp; 
     } 
if(root->value>nUser) 
    if(root->left) 
     { 
     addnode(root->left,nUser); 
     } 
    else 
     { 
     node *temp; 
     temp=(node *)malloc(sizeof(node)); 
     temp->value=nUser; 
     root->left=temp; 
     } 
} 
int checknode (node *root, int nUser) 
{ 
    if(!(root->value==nUser)) 
    { 
     if(root->value<nUser) 
      if(root->right) 
       { 
       checknode(root->right,nUser); 
       } 
      else 
       { 
       return(0); 
       } 
     if(root->value>nUser) 
      if(root->left) 
       { 
       checknode(root->left,nUser); 
       } 
      else 
       { 
       return(0); 
       } 
    } 
    else 
    { 
     return (1); 
    } 
} 

ответ

0
root=(node *)malloc(sizeof(node)); 

Изменить на:

root=(node *)calloc(1, sizeof(node)); 

Вы не ясно root->left и root->right в NULL, так что вы используете неинициализированные указатели. Вы должны изменить все свои malloc на calloc, или вам нужно очистить левый и правый указатели до NULL после каждого malloc.

1

Я думаю, что проблема в том, что указатели на корень left и right неинициализируются, когда вы передаете корень в addnode. Буфер, возвращаемый malloc, не может быть NULL.

Попробуйте инициализировать root->right и root->left до NULL перед началом цикла.

Смежные вопросы