트리 삭제 작업

1991 단어
#include <stdio.h>

class Node
{
public:
	Node * left;
	Node * right;
	Node * pre;
	int data;
	Node(int d,Node* p=NULL):data(d),left(0),right(0),pre(p)
	{}
};

void insert(Node* head,int a)
{
	if(head->data > a)
	{
		if(head->left==NULL) head->left=new Node(a,head);
		else insert(head->left,a);
	}else
	{
		if(head->right==NULL) head->right=new Node(a,head);
		else insert(head->right,a);
	}
}
void preorder_print(Node* d)
{
	if(!d) return;
	preorder_print(d->left);
	printf("%d ",d->data);
	preorder_print(d->right);
}
void transplant(Node* d,Node *u,Node *r)
{
	if(u->pre==NULL){
		*d=*r;
		delete r;
	}
	else if(u->pre->left==u)
		u->pre->left=r;
	else
		u->pre->right=r;
	if(r)
		r->pre=u->pre;
	delete u;
}
//find minnum node
Node* minnum_node(Node* d)
{
	if(d->left==NULL) return d;
	return minnum_node(d->left);
}
//delete the first where data equals 'num'
void delete_node(Node* root,Node* d,int num)
{
	if(d->data==num)
	{
		if(d->left==NULL) transplant(root,d,d->right);
		else if(d->right==NULL) transplant(root,d,d->left);
		else
		{
			auto min=minnum_node(d->right);
			if(min->pre!=d)
				transplant(root,min,min->right);
			transplant(root,d,min);
			min->pre=d->pre;
			min->right=d->right;
			min->right->pre=min;
			min->left=d->left;
			min->left->pre=min;
			delete d;
		}
	}
	else if(d->data>num) delete_node(root,d->left,num);
	else delete_node(root,d->right,num);
}
void release(Node* d)
{
	if(d->left!=NULL) release(d->left);
	if(d->right!=NULL) release(d->right);
	delete d;
}
int main()
{
	Node* head=new Node(5);
	int data[]={1,6,2,4,7,9,10,3};
	for(int i=0;i<sizeof(data)/sizeof(int);++i)
		insert(head,data[i]);
	preorder_print(head);
	putchar('
'); delete_node(head,head,3); preorder_print(head); putchar('
'); release(head); return 0; }

좋은 웹페이지 즐겨찾기