Reputation: 233
I have to put nodes of binary search tree of every level in a linked list. That is if the height of the tree is 'h' then 'h+1' linked lists would be created and then each linked list would have all the nodes of each level. For this I have thought of creating an array of linked list. But the nodes are not being inserted in the list I guess. The code is as follows:-
struct node{
int data;
struct node *left;
struct node *right;
};
struct linked_list
{
int data;
struct linked_list *next;
};
linkedlistofbst(struct node *new,struct linked_list *n1[], int level)
{
//printf("%d ",new->data);
if(new==NULL)
{
return;
}
if(n1[level]==NULL)
{
struct linked_list *a =(struct linked_list *)malloc(sizeof(struct linked_list));
a->data=new->data;
a->next=NULL;
n1[level]=a;
printf("%d ",a->data);
}
else
{
struct linked_list *b =(struct linked_list *)malloc(sizeof(struct linked_list));
while(n1[level]->next!=NULL)
{
n1[level]=n1[level]->next;
}
b->data=new->data;
b->next=NULL;
n1[level]=b;
}
linkedlistofbst(new->left,n1,level+1);
linkedlistofbst(new->right,n1,level+1);
}
main()
{
struct linked_list *l=(struct linked_list *)malloc((a+1)*sizeof(struct linked_list));//'a' is the height of the tree
linkedlistofbst(new,&l, 0);//new is the pointer to the root node of the tree.
}
Upvotes: 1
Views: 133
Reputation: 8292
You are right there is problem with the second argument, so do the following
Make the following changes in the main:
For defining an array of linked list of size a+1 and initializing them to NULL
struct linked_list **l=(struct linked_list **)malloc((a+1)*sizeof(struct linked_list*));
for(i=0;i<(a+1);++i)
l[i]=NULL;
Then call the method as
linkedlistofbst(new,l, 0);
Therefore your method must look like
linkedlistofbst(struct node *new,struct linked_list **l, int level)
also make the following modification in else as:
else
{
struct linked_list *ptr=n1[level];
while(ptr->next!=NULL)
{
ptr=ptr->next;
}
ptr->next=(struct linked_list *)malloc(sizeof(struct linked_list));
ptr->next->data=new->data;
ptr->next->next=NULL;
}
Upvotes: 1