Reputation: 609
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
Upvotes: 0
Views: 446
Reputation: 44230
#include <stdio.h>
#include <stdlib.h>
struct node {
struct node *left;
struct node *right;
int ele;
};
void intrav(struct node * ptr);
void ins(int xxx,struct node **hnd );
void ins(int xxx,struct node **hnd )
{
while (*hnd) {
hnd = xxx < (*hnd)->ele ? &(*hnd)->left : &(*hnd)->right;
}
*hnd = malloc(sizeof **hnd);
(*hnd)->left = NULL;
(*hnd)->right = NULL;
(*hnd)->ele = xxx;
}
void intrav(struct node * ptr)
{
if (!ptr) return;
intrav(ptr->left);
printf("%d\n", ptr->ele);
intrav(ptr->right);
}
int main()
{
int no,i,elem[50];
struct 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]);
//printf("%d---",root);
for(i=0;i<no;i++)
ins(elem[i], &root);
// printf("%d",root->left);
intrav(root);
getc(stdin);
return 0;
}
Upvotes: 0
Reputation: 2186
The problem is on the two malloc
s, but I think that this is a homework, so I will not tell you exactly what it is.
HINT: Check what type NODE
is!
Upvotes: 2