Q:

Implementing the Binary Tree in C

I am trying to implement the Binary tree in C.Firstly inserting the values and then traversing them into the Preorder.But when i call the function preorder() then it's giving me infinite loop with only last value inserted.
I am using following code:
struct node* insert(struct node *root,int num);

void preorder(struct node *root);

struct node *root=NULL;

int count=1;

struct node {

    struct node *lchild;
    struct node *rchild; 
int data;
};

int main(){

    root=insert(root,1);
//root=insert(root,2);
preorder(root); 
return;
}

struct node* insert(struct node *root,int num){//insert a node into tree

   //struct node *q;
if(root==NULL)
{
    root=(struct node*)malloc(sizeof(struct node)); 
    root->data=num;
    root->lchild=NULL;
    root->rchild=NULL;
    //root=q;
    count++;
}
else{
    if(count % 2==0){
        root->lchild=insert(root->lchild,num);
    }
    else{
        root->rchild=insert(root->rchild,num);
    }
}
return(root);
}

void preorder(struct node *root){

    while(root!=NULL){
    printf("%d\t",root->data);
    preorder(root->lchild);
    preorder(root->rchild);     
}
}

here i am inserting only 1 value initially but the bug occurs.So in insert() there should not be any mistake,something correction should be done in preorder() or main()..what it can be?

A:

I am not sure what preorder() should do, but this line causes the endless loop:
 while(root!=NULL){

I guess you meant to write if not while

