Binary Search Tree implementation.

Joined
Aug 5, 2008
Messages
1
Reaction score
0
I am trying to write a implmentation of binary search tree(BST) in C.
* The implmentation takes several integers from user
* Add the integers to the BST
* Any duplicate number is discarded

I implimented the program using linked list but i am getting segmentation fault instead.
I tried inserting various printf for debugging but i am unable to find the exact error.
It seems that the error is in the insert2 function.

Here is the implementation:-

----------------------------------
#include <stdio.h>
#include <stdlib.h>


/*----------Type definations-----------*/
typedef struct node{
int data; //Data
struct node * left; //Left Node
struct node * right; //Right Node
}node;



/*---------Function Prototypes----------*/
void insert2(node *, node *); //insert node in tree
node * new_Node();



/*---------Main Function---------------*/
int main()
{
int n;
int i;
int temp;
node * temp_n;
node * root;
root == NULL;

printf("Enter number of inputs to be given:");
scanf("%u", &n);

//Take input from user and insert it in the BST

for(i = 0; i < n; i++){
printf("?");
scanf("%d", &temp);
/*--Debug Code1--*/
// printf("%d", temp);

temp_n = new_Node();
//printf("Temp_Node testing\n");
temp_n->data = temp;

//DEBUG Code2
//printf("%d\n", temp_n);
printf("Temp_n data %d\n", temp_n->data);

//DEBUG CODE
//printf("%d %d\n", &int_bst, sizeof(int_bst));
printf("Calling insert2");

insert2(root, temp_n);
}
}


/*--------Function Declaration----------*/
node * new_Node(){
node * temp = (node *) malloc(sizeof(node));

temp->data = 0;
temp->left = NULL;
temp->right = NULL;

return temp;
}



void insert2(node * r, node * c)
{
//DEBUG CODE
printf("In insert2");

if(r == NULL){
r = new_Node(); //BASE Condition
r = c;
}
else{
if(c->data == r->data){
//DEBUG CODE
printf("DUPLICATION DETECTED\n");
}
else if(c->data < r->data){
insert2(r->left, c);
}
else if(c->data > r->data){
insert2(r->right, c);
}
}
}

-----------------------

Sample Output:-

Enter number of inputs to be given:3
?2
Temp_n data 2
Segmentation fault

------------------------

Please help me to find the actual bug in my implementation.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,020
Latest member
GenesisGai

Latest Threads

Top