i am trying to write binary tree program in c.
but its not printing the values. and it is not coming out of while loop.
this is the code i tried
Code:
#include <stdio.h>#include <stdlib.h>
typedef struct node {
int data;
struct node* left;
struct node* right;
}node;
int n;
int main()
{
node *root, *first, *current, *temp; int num,i;
printf("How many no.\n");
scanf("%d", &n);
root=(node*)malloc(sizeof(node));
first = root;
printf("Enter no.");
scanf("%d", &root->data);
for(i=1;i<n;i++) {
current=first;
temp = (node*)malloc(sizeof(node));
printf("Enter no.");
scanf("%d", &num);
temp->data=num;
if(num<current->data) {
current->left=temp;
}
else current->right=temp;
first=current;
}
temp->left=NULL;
temp->right=NULL;
current=root;
while(current->left!=NULL || current->right!=NULL) {
printf("%d\n", current->data);
current=current->left;
}
return 0;
}
this code is printing infinte garbage values. can anyone tell me how write program to implement binary tree?