I'm a computer engineering student and I have to write BST as an assignment but the code is not like what everyone written(so far as I search for some example,so I'm desperate now) Here is my code so far(My classroom use C as a main language not C++)
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
typedef struct bst_node
{
int data;
struct bst_node *right;
struct bst_node *left;
}BST_NODE;
typedef struct bst
{
int size;
BST_NODE *root;
}BST;
void print(BST_NODE *pos)
{
printf("%d(0)",pos->data);
if(pos->left != NULL)
{
printf("%d(L)\n",pos->left->data);
pos=pos->left;
}
if(pos->right != NULL)
{
printf("%d(R)\n",pos->right->data);
pos=pos->right;
}
if(pos->left != NULL)
print(pos->left);
if(pos->right != NULL)
print(pos->right);
}
int main()
{
int number;
BST b;
BST_NODE *pos;
b.root=NULL;
while(1)
{
scanf("%d",&number);
printf("value=%d",number);
if(number<=0)
break;
if(b.root==NULL)
{
b.root=(BST_NODE*)malloc(sizeof(BST_NODE));
pos=b.root;
pos->data=number;
pos->left=NULL;
pos->right=NULL;
}
else
{
pos=b.root;
while(pos)
{
if(number>pos->data)
{
if(pos->right==NULL)
{
pos->right=(BST_NODE*)malloc(sizeof(BST_NODE));
pos->right->left=NULL;
pos->right->right=NULL;
pos->right->data= number;
pos=pos->right;
}
else
{
pos->right->data= number;
pos=pos->right;
}
}
if(number<pos->data)
{
if(pos->left==NULL)
{
pos->left=(BST_NODE*)malloc(sizeof(BST_NODE));
pos->left->left=NULL;
pos->left->right=NULL;
pos->left->data=number;
pos=pos->left;
}
else
{
pos->left->data=number;
pos=pos->left;
}
}
}
}
}
print(b.root);
return 0;
}
I don't know what wrong with this code because it can only receives 2 value then it stops working. The only thing I found out so far to be a problem is while(pos)loop and I try to fix this for week.I would be grateful,if anyone help me solve this problem. Print it out to would be great. P.S -stop working mean the windows I run program in just freeze or hang.