Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

SOLVED: Where is the bug in this search code for a binary search tree?

Coderandhacker:

I have written this code for strict Binary Search trees. (If every non-leaf Node in a binary tree has nonempty left and right subtrees, the tree is termed a strictly binary tree. Or, to put it another way, all of the nodes in a strictly binary tree are of degree zero or two, never degree one. A strictly binary tree with N leaves always contains 2N – 1 nodes.) Unfortunately, it's not printing values correctly. I don't know what's the problem. I have seen other sites on the internet and the code is nearly same but still, I can't find a bug in my code.


#include
#include
struct node
{
struct node* prev;
int data;
struct node* next;
};
void Binary_Search_Tree(struct node *newnode,struct node *p);
void print(struct node* p);

main()
{
struct node *root,*nnode,*temp;
int c,d;
root=malloc(sizeof(struct node));

printf("Enter the root data\t");
scanf("%d",&d);
root->data=d;
root->prev=NULL;
root->next=NULL;

while(1)
{
printf("Enter your choice\n1 insert element.\n2 print tree.\n3 Exit");
scanf("%d",&c);
switch(c)
{
case 1:
nnode=malloc(sizeof(struct node));
printf("Enter the node data\t");
scanf("%d",&d);

nnode->data=d;
nnode->prev=NULL;
nnode->next=NULL;
temp=root;

Binary_Search_Tree(nnode,temp);
break;
case 2:
temp=root;
print(temp);
break;
case 3:
free(root);
free(nnode);
free(temp);
temp=nnode=root=NULL;
exit(1);
break;
}
}
return 0;
}

void Binary_Search_Tree(struct node *newnode,struct node *p)
{

if(newnode->datadata)
{
if(p->prev=NULL)
{
p->prev=newnode;
}
else if(p->prev!=NULL)
{
p=p->prev;
Binary_Search_Tree(newnode,p);
}
}
else if(newnode->data>p->data)
{
if(p->next=NULL)
{
p->next=newnode;
}
else if(p->next!=NULL)
{
p=p->next;
Binary_Search_Tree(newnode,p);
}
}
}

void print(struct node* p)
{
if(p!=NULL)
{
print(p->prev);
printf("%d\n",p->data);
print(p->next);
}
}



Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
This Question have been answered
HERE


This post first appeared on Stack Solved, please read the originial post: here

Share the post

SOLVED: Where is the bug in this search code for a binary search tree?

×

Subscribe to Stack Solved

Get updates delivered right to your inbox!

Thank you for your subscription

×