0

I wrote this simple program in C to generate binary search tree, but i am unable to go beyond level 0. Note that I have not incorporated the printing part.

#include<stdio.h>
#include<malloc.h>
struct node {
       int data;
       struct node *lc;
       struct node *rc;
       }*start,*link,*tmp;
       int a[100];

int main()
{
int i,n,flag;
start=NULL;
printf("how many integers you wish to enter\n");
scanf("%d",&n);
for(i=0;i<n;i++) 
{
scanf("%d",&a[i]);

tmp=(struct node*)malloc(sizeof(struct node));
tmp->data=a[i];
tmp->lc=NULL;
tmp->rc=NULL;
flag=0;
if(start==NULL) start=tmp;
else {
    
     link=start;     
while(link!=NULL)
{

if(link->data==a[i]) {printf ("The element already exists");flag=1;break;}
else if(a[i]>link->data) {link=link->rc;printf("rc\n");}
else if(a[i]<link->data) {link=link->lc;printf("lc\n");}
}
if(flag==0) link=tmp
}


}

getch();
return 0;
}
2
Contributors
1
Reply
3
Views
7 Years
Discussion Span
Last Post by Narue
1

Once link becomes a null pointer, you've left the realm of the tree. Assigning to link at that point does nothing productive. What you need to do is save a pointer to the last node before link become null, and then assign tmp to either the lc or rc link (depending on the direction you're moving) of that node:

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

struct node {
    int data;
    struct node *lc;
    struct node *rc;
};

int main()
{
    struct node *start = NULL;
    int i,n,flag;

    printf("how many integers you wish to enter\n");
    scanf("%d",&n);

    for(i=0;i<n;i++) {
        struct node *tmp = malloc(sizeof(struct node));
        int a;

        scanf("%d",&a);

        tmp->data=a;
        tmp->lc=NULL;
        tmp->rc=NULL;
        flag=0;

        if (start==NULL)
            start=tmp;
        else {
            struct node *last = start;
            struct node *link = start;

            while (link!=NULL) {
                last = link;
                if (link->data==a) {
                    printf ("The element already exists");
                    flag=1;
                    break;
                }
                else if (a>link->data) {
                    link=link->rc;
                    printf("rc\n");
                }
                else if (a<link->data) {
                    link=link->lc;
                    printf("lc\n");
                }
            }

            if (flag==0) {
                if (a > last->data)
                    last->rc = tmp;
                else
                    last->lc = tmp;
            }
        }
    }

    return 0;
}
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.