赞
踩
编写算法实现对依次输入的关键字序列建立二叉排序树,并能 实现二叉排序树的查找、插入和删除运算。
- #include<cstdio>
- #include<iostream>
- #include<cstdlib>
- using namespace std;
- #define KeyType int
-
- typedef struct
- {
- KeyType key;
- char name[20];
- }ElemTyped;
-
- typedef struct BSTNode
- {
- ElemTyped data;
- struct BSTNode *lchild,*rchild;
- }BSTNode,*BSTree;
-
- void SearchBST(BSTree T,KeyType key){
- if((T==NULL)||key==T->data.key){
- printf("关键字:%d\n名称:%s\n\n",T->data.key,T->data.name);
- return ;
- }
- else if(key<T->data.key&&(T->lchild!=NULL))
- return SearchBST(T->lchild,key);
- else if(key>T->data.key&&(T->rchild!=NULL))
- return SearchBST(T->rchild,key);
- else{
- printf("没有该关键字!\n\n");
- return ;
- }
- }
-
- void InsertBST(BSTree &T,ElemTyped e){
- BSTree s;
- if(T==NULL){
- s=new BSTNode;
- s->data=e;
- s->lchild=s->rchild=NULL;
- T=s;
- }
- else if(e.key<T->data.key)
- InsertBST(T->lchild,e);
- else
- InsertBST(T->rchild,e);
- }
-
- void CreatBST(BSTree &T){
- T=NULL;
- ElemTyped e;
- printf("请输入关键字个数:\n");
- int n;
- scanf("%d",&n);
- printf("请输入关键字:\n");
- for(int i=1;i<=n;i++){
- cin>>e.key>>e.name;
- InsertBST(T,e);
- }
- printf("创建成功!\n\n");
- system("Pause");
- system("cls");
- }
-
- void DeleteBST(BSTree &T,KeyType key){
- BSTree p,f,q,s;
- p=T;f=NULL;
- while(p){
- if(p->data.key==key)
- break;
- f=p;
- if(p->data.key>key)
- p=p->lchild;
- else
- p=p->rchild;
- }
- if(!p)
- return ;
- q=p;
- if((p->lchild)&&(p->rchild)){
- s=p->lchild;
- while(s->rchild){
- q=s;
- s=s->rchild;
- }
- p->data=s->data;
- if(q!=p)
- q->rchild=s->lchild;
- else
- q->lchild=s->lchild;
- delete s;
- return;
- }
- else if(!p->rchild){
- p=p->lchild;
- }
- else if(!p->rchild)
- p=p->rchild;
- if(!f)
- T=p;
- else if(q==f->lchild)
- f->lchild=p;
- else
- f->rchild=p;
- delete q;
- printf("删除成功!\n");
- system("Pause");
- system("cls");
- }
-
- int main()
- {
- BSTree T;
- while(1){
- printf("--------二叉排序树---------\n\n");
- printf(" 1.创建.\n");
- printf(" 2.查找.\n");
- printf(" 3.插入.\n");
- printf(" 4.删除.\n");
- printf(" 5.退出.\n\n");
- printf("---------------------------\n\n");
- printf("请输入您的选择:\n");
- int a;
- scanf("%d",&a);
- if(a==5){
- printf("谢谢使用!\n");
- break;
- }
- if(a!=1&&a!=2&&a!=3&&a!=4&&a!=5){
- printf("您输得不符合要求,请重新出入!\n");
- continue;
- }
- switch(a){
- case 1:CreatBST(T);break;
- case 2:
- printf("请输入要查找的关键字:\n");
- KeyType e;
- cin>>e;
- SearchBST(T,e);
- system("Pause");
- system("cls");
- break;
- case 3:
- ElemTyped e1;
- printf("请输入要插入的关键字和名称:\n");
- cin>>e1.key>>e1.name;
- InsertBST(T,e1);
- printf("插入成功!\n");
- system("Pause");
- system("cls");
- break;
- case 4:
- KeyType e2;
- printf("请输入要删除的关键字:\n");
- cin>>e2;
- DeleteBST(T,e2);
- break;
- }
- }
- return 0;
- }
-
- /*
- 45 CAO
- 12 ZHAO
- 53 DING
- 61 CHEN
- 37 WANG
- 24 LI
- 90 XIA
- 79 DU
- 3 MA
- 100 XYU
- */

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。