well i was creating a binary search tree using this code..as far as i as see using this code i find it to be correct but some how its creating error i dont know why
#include<stdio.h>
#include<conio.h>
#include<malloc.h>
typedef struct node
{
struct node *left;
int ele;
struct node *right;
}*NODE;
void ins(int x,NODE root )
{
NODE temp;
//printf("%d %d*****%d---%d\n",root->ele,root,(root->left),(root->right)); if i uncomment this line and then (when this function takes first root as its argument )do trace over using turbo C++ compiler its giving me root->left value not null how ever it just executes the next if statement..this should have happened
if(x<(root->ele) && (root->left)==NULL)
{
temp=(NODE)malloc(sizeof(NODE));
temp->ele=x;
temp->left=NULL;
temp->right=NULL;
root->left=temp;
}
else if(x<root->ele && (root->left)!=NULL)
{
ins(x,root->left);
}
else if(x>(root->ele) && (root->right)==NULL)
{
temp=(NODE)malloc(sizeof(NODE));
temp->ele=x;
temp->left=NULL;
temp->right=NULL;
root->right=temp;
}
else if(x>(root->ele) && (root->right)!=NULL)
{
//printf("%d***%d***%d",root->ele,root->right->ele) ;
ins(x,root->right);
}
//printf("%d",x);
}
void intrav(NODE root)
{
if(root->left!=NULL)
intrav(root->left);
printf("%d",root->ele);
if(root->right!=NULL)
intrav(root->right);
}
void main()
{
int no,i,elem[50];
NODE root=NULL;
printf("enter the no of elements you want to enter\n");
scanf("%d",&no);
for(i=0;i<no;i++)
scanf("%d",&elem[i]);
root=(NODE)malloc(sizeof(NODE));
root->ele=elem[0];
root->left=NULL;
root->right=NULL;
//printf("%d---",root);
for(i=1;i<no;i++)
ins(elem[i],root);
// printf("%d",root->left);
intrav(root);
getch();
}
using for loop the ins function is executed every time that takes an array value every time and send it to the function…then if the value to be added
The problem is on the two
mallocs, but I think that this is a homework, so I will not tell you exactly what it is.HINT: Check what type
NODEis!