Naman
Naman

Reputation: 1041

Compilation Error in Construction of Binary Search tree

I am building a binary search tree. Here is the code:

#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;
}

I am getting a compilation error:

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

Why?

Upvotes: 0

Views: 68

Answers (2)

ryyker
ryyker

Reputation: 23218

Here:

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

tree is a pointer to pointer, and
and tem is a pointer
so statement:

*tem = *tree1;

should be:

tem = *tree1;

Upvotes: 1

Yu Hao
Yu Hao

Reputation: 122383

Inside if(value <= (*tree1)->val),

*tem = *tree1;

should be:

tem = *tree1;

You have the correct version in the else branch.

Upvotes: 2

Related Questions