I am reading integers from an input file which has some bunch of integers and trying to create a binary tree. I am not able to figure out why it is going in (l==NULL) all the time. For the second time it should go to left or right depending on whether read value is greater than root value or not.
Appreciate any help. Thanks!
leaf* create_leaf(int i)
{
leaf* l = (leaf*)malloc(sizeof(leaf));
l->left = NULL;
l->right = NULL;
l->data = i;
}
leaf* l=NULL;
while(fscanf(input,"%d",&i) != EOF)
{
add_leaf(l,i);
}
void add_leaf(leaf* l, int i)
{
if(l == NULL)
{
printf("adding root\n");
l = create_leaf(i);
}
else if(i <= l->data)
{
if(l->left == NULL)
{
l->left = create_leaf(i);}
else {
add_leaf(l->left,i); }
}
else
{
if(l->right == NULL)
{
l->right = create_leaf(i); }
else {
add_leaf(l->right,i); }
}
}
When you reassign
linadd_leaf(), the new value ofldoesn’t propagate to the caller when the function returns.You have two options:
leaf** l, and change your code accordingly.returnthe newlfrom the function.