Witam was. Tym razem pisze program z drzewem BST.
Niestety cos jest nie tak, moze wy mnie naprowadzicie. Przy usuwaniu elementu, ktory ma 2 wezly kolejne jest problem, i takze mam problem, gdy chce usunac korzen. Macie jakies pomysly jak ten moj kod naprostowac? Jakiekolwiek refleksje milo widziane!
void rm(struct bush* &root, int x)
{
struct bush* parent;
struct bush* p;
struct bush* preparent;
struct bush* child;
struct bush* grandchild;
parent=NULL;
p=root;
while((p!=NULL) && x!=(p->key))
{
parent=p;
if((p->key)<x)
p=(p->R);
else
p=p->L;
}
if(p==NULL) return;
if((p->R)==NULL && (p->L)==NULL)
{
if(p==root)
{
root=NULL;
return;
}
if((parent->R)==p)
(parent->R)=NULL;
else
(parent->L)=NULL;
return;
}
if(p->R==NULL)
{
if((parent->R)==p)
(parent->R)=(p->L);
else
(parent->L)=(p->L);
return;
}
if((p->L)==NULL)
{
if((parent->R)==p)
(parent->R)=(p->R);
else
(parent->L)=(p->R);
return;
}
///Do tego momentu wydaje sie ok?
preparent=p;
child=(p->L);
while((child->R)!=NULL)
{
preparent=child;
child=(child->R);
}
if(child==(p->L))
{
if((parent->R)==p)
(parent->R)=child;
else
(parent->L)=child;
return;
}
grandchild=(child->L);
if((preparent->R)==child)
(preparent->R)=grandchild;
else
(preparent->L)=grandchild;
(child->L)=(p->L);
if((parent->R)==p)
(parent->R)=child;
else
(parent->L)=child;
return;
};