BST的删除
#include<iostream> #include<math.h> #include<stdio.h> #include<stdlib.h> #include<windows.h> #include<string.h> //const MAX=50; using namespace std; struct BitreeNode{ //int num=1; int data; BitreeNode *lchild; BitreeNode *rchild; }; typedef struct BitreeNode *Bitree; //typedef t p; bool Delete(Bitree *t); void pre_order(BitreeNode *t)// { if(t==NULL) { return ; } cout<<t->data<<" "; pre_order(t->lchild); pre_order(t->rchild); return; } void in_order(BitreeNode *t)// { if(t==NULL) { return; } in_order(t->lchild); cout<<t->data<<" "; in_order(t->rchild); return; } void insert_tree(int data,BitreeNode *&t)//二查搜索树的建立 { if(t==NULL)// { t=new BitreeNode; t->data=data; //strcpy(t->data,data); t->lchild=NULL; t->rchild=NULL; return; } if( (t->data)<data ) { insert_tree(data,t->rchild); } if( (t->data)>data ) { insert_tree(data,t->lchild); } return; } Bitree foundNode(int x,Bitree t)//寻找结点 //返回该结点的地址 { if(t==NULL) { cout<<"No Found!"; return NULL; } if(x>(t->data)) { return foundNode(x,t->rchild); } if(x<(t->data)) { return foundNode(x,t->lchild); } if(x==(t->data)) { //cout<<x; //t=NULL; //--- ///delete t; //---- return t; } //return; } int deletemin(Bitree t)//删除最小的结点 { if(t==NULL) { cout<<"空树"; return -1; } if(t->lchild==NULL)//根节点左空 { cout<<"最小的结点是根节点无法删除:"<<t->data<<endl; return -1; } if((t->lchild->lchild)==NULL) { //cout<<t->lchild->data<<endl; //delete t->lchild; //删除 //t->lchild=NULL; int a=t->lchild->data;//封装最小结点 t->lchild=t->lchild->rchild;//删除最小结点 return a; } return deletemin(t->lchild); //return; } bool deleteBST(int x,Bitree *t)//删除某个结点 { if((*t)==NULL) { return 0; } if((*t)->data>x)//x小于当前 { return deleteBST(x,&(*t)->lchild); } if((*t)->data<x)//x大于当前 { return deleteBST(x,&(*t)->rchild); } if((*t)->data==x)//x等于于当前 { return Delete(t); } } bool Delete(Bitree *t)//给入要删除的结点t的指针 { Bitree q,s; if((*t)->lchild==NULL)//左空 { q=*t; (*t)=(*t)->rchild; delete (q); return 1; } if((*t)->rchild==NULL)//右空 { q=*t; (*t)=(*t)->lchild; delete (q); return 1; } q=*t ; s=(*t)->lchild; while(s->rchild!=NULL) { q=s; s=s->rchild; } (*t)->data=s->data; if(q!=*t) { q->rchild=s->lchild; } else { q->lchild=s->lchild; } return 1; } //bool Delete() int main() { freopen("bin.txt","r",stdin); //int j=0; //CreateTree(T); //j=rand()%10;// //pre_order(T); //cout<<"\n"; //in_order(T); //char st[MAX]; //F=foundNode(18,T); //cout<<F->data; //cout<<deletemin(T->rchild->rchild); //in_order(T); BitreeNode *T=NULL;//*F=NULL;// int num=0; for(int i=1;i<=12;i++) { //gets(st); cin>>num; insert_tree(num,T); } deleteBST(12,&T); in_order(T); return 0; }