I've got problem when i'm using inorder fuction after delete a data from BST
usually if i don't use delete function i can print data by use inorder fuction normally.
and the second problem is when i want to delete node that doesn't have a children the problem will show because the node that i would delete is nothing happening example
9
5 10
DATA >>
11
/ \
5 18
/ \
16 24
/ \
15 17
<<<
Code:
#include<stdio.h>
#include<conio.h>
typedef struct treetype
{
int num;
struct treetype *left;
struct treetype *right;
}T;
void insertnode(T **bst,T *p)
{
T *prev,*start;
start=*bst;
int flag=-1;
if(*bst==NULL)
{
(*bst)=p;
printf("\nCreate parent node >> %d",(**bst).num);
}
else
{ while(start!=NULL)
{
prev=start;
if((*p).num>(*start).num)
{
start=(*start).right;
flag=0;
}
else
{
start=(*start).left;
flag=1;
}
}
if(flag==0)
{
(*prev).right=p;
printf("\nAdd %d to right of %d",(*p).num,(*prev).num);
}
else if(flag==1)
{
(*prev).left=p;
printf("\nAdd %d to left of %d",(*p).num,(*prev).num);
}
else
printf("\nCannot insert node");
}
}
void deletebst(T **bst,int target)
{
T *start,*prev;
start=*bst;
while(start!=NULL)
{
prev=start;
if(target<(*start).num)
start=(*start).left;
else if(target>(*start).num)
start=(*start).right;
else
{
if((*start).right==NULL)
{
start=(*start).left;
delete prev;
}
else if((*start).left==NULL)
{
start=(*start).right;
delete prev;
}
else
{
prev=(*start).left;
while((*prev).right!=NULL)
prev=(*prev).right;
(*start).num=(*prev).num;
delete prev;
}
}
}
}
void getdata(T **bst)
{
FILE *inf;
T *p;
inf=fopen("data.txt","r");
*bst=NULL;
while(!feof(inf))
{
p=new T;
fscanf(inf,"%d",&(*p).num);
(*p).right=(*p).left=NULL;
insertnode(bst,p);
}
printf("\nFinishing");
}
void inorder(T *bst)
{
if(bst!=NULL)
{
inorder((*bst).left);
printf("%d ",(*bst).num);
inorder((*bst).right);
}
}
void main()
{
T *bst,*prev;
int ans;
clrscr();
getdata(&bst);
printf("\n");
inorder(bst);
deletebst(&bst,11);
printf("\n");
inorder(bst);
getch();
}