2013-10-26 3 views
0

Я строю двоичное дерево поиска. Вот код:Ошибка компиляции в построении дерева двоичного поиска

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


struct tree_node 
{ 
    int val; 
    struct tree_node *left; 
    struct tree_node *right; 
}; 
void insert(struct tree_node **, int); 
int main(void) 
{ 
    struct tree_node *tree; 

    tree = NULL; 
    insert(&tree, 10); 
    insert(&tree, 20); 
    insert(&tree, 5); 
    insert(&tree, 7); 

    return 0; 
} 

void insert(struct tree_node **tree1, int value) 
{ 
    struct tree_node *temp, *start, *tem; 
    tem = NULL; 
    temp = (struct tree_node *)malloc(sizeof(struct tree_node)); 
    start = *tree1; 

    temp->val = value; 
    temp->left = NULL; 
    temp->right = NULL; 

    if(*tree1 == NULL) 
     *tree1 = temp; 
    else 
    { 
     while(*tree1 != NULL) 
     { 
      if(value <= (*tree1)->val) 
      { 
       *tem = *tree1; 
       *tree1 = (*tree1)->left; 
      } 
      else 
      { 
       tem = *tree1; 
       *tree1 = (*tree1)->right; 
      } 

     } 
     if((tem->left) == *tree1) 
      tem->left = temp; 
     else 
      tem->right = temp; 
    } 
    *tree1 = start; 
} 

Я получаю ошибку компиляции:

prog.c:44:5: error: invalid operands to binary * (have ‘struct tree_node *’ and ‘struct tree_node **’) 

Почему?

+1

Вы s hould '#include ' для 'malloc()', вместо '# include'ing' 'дважды, между прочим. Пока мы обсуждаем этот вопрос, вы должны написать 'temp = malloc (sizeof (* temp));' –

ответ

2

Внутри if(value <= (*tree1)->val),

*tem = *tree1; 

должно быть:

tem = *tree1; 

Вы имеете правильную версию в else отрасли.

+0

Oh Thanks Yu Hao !!! – Naman

+0

Эй, как я могу напечатать значение root. Я делаю printf ("% d", tree-> val); в main(), но при этом вы получите сообщение об ошибке RUN TIME ERROR. – Naman

+0

@Naman - это правильно. temp-> значение будет печататься с этим утверждением. – ryyker

1

Здесь:

void insert(struct tree_node **tree1, int value) 

tree является указателем на указатель, и
и tem указатель
так заявление:

*tem = *tree1; 

должно быть:

tem = *tree1; 
Смежные вопросы