I was trying to make a simple binary tree
When i ran it, turbo C terminated
while it wrkd fine when i compiled using gcc
I used a count variable to keep a check in the loop....and the value of count had gone upto 25 when it should have been just 3
(this happened when i entered numbers 7 6 5 8)
Code:
#include<stdio.h>
#include<conio.h>
struct nodetype
{
int info;
struct nodetype *rt;
struct nodetype *lt;
};
typedef struct nodetype *node;
node getnode()
{
node tmp=(node)malloc(sizeof(node));
return tmp;
}
node maketree(int x)
{
node p= getnode();
if(p==NULL)printf("No space");
p->info=x;
p->lt=NULL;
p->rt=NULL;
return(p);
}
void setleft(node q, int x)
{
node tmp;
if(q==NULL)
{
printf("Father null");
return;
}
if(q->lt!=NULL)
{
printf("Invalid insertion");
return;
}
q->lt= maketree(x);
}
void setright(node q, int x)
{
node tmp;
if(q==NULL)
{
printf("Father null");
return;
}
if(q->rt!=NULL)
{
printf("Invalid insertion");
return;
}
q->rt= maketree(x);
}
void insert(node *tree, int x)
{
int count=0;
node p,q;
p=q= *tree;
if(p== NULL)
{
printf("tree");
*tree=maketree(x);
return;
}
while((p->info!=x)&&(q!=NULL))
{
p=q;
//count++;
if(q->info>x)
q=q->lt;
else
q=q->rt;
//printf("count: %d" , count);
}
if(x==p->info)
printf("Number already exixts");
else
{
if(x>p->info)
setright(p,x);
else
setleft(p,x);
}
}
//For inorder traversal of the tree
void intrav(node p)
{
if(p!=NULL)
{
intrav(p->lt);
printf(" %d ", p->info);
intrav(p->rt);
}
}
void main()
{
int num;
node mytree= NULL;
clrscr();
do
{
printf("NUMBER: ");
scanf("%d", &num);
insert(&mytree, num);
printf("\nEnter more: ");
scanf("%d", &num);
}while(num==1);
intrav(mytree);
getch();
}
I would highly appreciate if someone would go through the code and point out my problem
Thanks