Usuwanie elementu z drzewa BST.

0

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;

};
0

debugger

0

Tryed, ale nie potrafię do tego dojść niestety.

0

A jak się ten problem objawia?

0

Więc, jeśli usuwam korzeń, to się program sypie, i w momencie, kiedy chce usunąć węzeł, który jest 2 stopnia ( ma 2 potomków).

1 użytkowników online, w tym zalogowanych: 0, gości: 1