The following procedure creates, inserts, and deletes a binary sorting tree!
#include<iostream>#include<vector>using namespace std;struct LNode{ int data; LNode *lchild; LNode *rchild;};void buildtree(LNode *root,LNode *q){ LNode *p=root; while(1){ if(q->data==p->data) break; else{ if((q->data)>(p->data)){ if(p->rchild!=NULL) p=p->rchild; else{ p->rchild=q; break; } } else{ if(p->lchild!=NULL) p=p->lchild; else{ p->lchild=q; break; } } } }}void del(LNode *root,LNode *q){ LNode *p=root; LNode *r; while(1){ if(p->data==q->data){ if(p->lchild==NULL&&p->rchild==NULL){ if(r->lchild==p) r->lchild=NULL; else r->rchild=NULL; delete p; break; } if(p->lchild==NULL&&p->rchild!=NULL){ if(r->lchild==p) r->lchild=p->rchild; else r->rchild=p->rchild; delete p; break; } if(p->lchild!=NULL&&p->rchild==NULL){ if(r->lchild==p) r->lchild=p->lchild; else r->rchild=p->lchild; delete p; break; } if(p->lchild!=NULL&&p->rchild!=NULL){ LNode *q; if(!p->lchild){ q=p->lchild; while(!(q->rchild)) q=q->rchild; p->data=q->data; delete q; break; } else{ q=p->rchild; while(!(q->lchild)) q=q->lchild; p->data=q->data; delete q; break; } } } else{ if((p->data)>(q->data)){ r=p; p=p->lchild; } else{ r=p; p=p->rchild; } } }}void inorder(LNode *root){ if(root){ inorder(root->lchild); cout<<root->data<<" "; inorder(root->rchild); }}int main(){ vector<int> sevc; int ch; while(cin>>ch&&ch!=0) sevc.push_back(ch); vector<int>::iterator iter; iter=sevc.begin(); LNode *root=new LNode; root->data=*iter; root->lchild=NULL; root->rchild=NULL; ++iter; LNode *p; for(;iter!=sevc.end();++iter){ p=root; LNode *q=new LNode; q->data=*iter; q->lchild=NULL; q->rchild=NULL; buildtree(p,q); } p=root; inorder(p); cout<<endl; cin.ignore(); p=root; cin>>ch; LNode *q=new LNode; q->data=ch; q->lchild=NULL; q->rchild=NULL; del(p,q); p=root; inorder(p); cout<<endl; delete p; delete q; delete root; return 0;}
This article is from the "cainiao's advanced road" blog, please be sure to keep this source http://beyond316.blog.51cto.com/7367775/1266364