实验 二叉排序树
来源:互联网 发布:吉首大学网络教学 编辑:程序博客网 时间:2024/06/06 03:35
掌握二叉排序树的查找、插入、删除、建立算法的思想及程序实现。
代码:
#include <bits/stdc++.h>using namespace std;typedef struct Node{ Node *ls,*rs; int val;}Node;typedef struct BSTree{ Node *root; BSTree(){root=NULL;}public: Node* newnode(){ Node *p=(Node*)malloc(sizeof(Node)); p->ls=p->rs=NULL; return p; } string Search(int x,Node *a){ if(a->val==x){ return " "; } if(a->val>x) return "0"+Search(x,a->ls); return "1"+Search(x,a->rs); } Node* Insert(int x,Node *a){ if(a==NULL){ a=newnode(); a->val=x; }else if(a->val>x){ a->ls=Insert(x,a->ls); }else{ a->rs=Insert(x,a->rs); } return a; } Node* Delete_Search(int x,Node *a){ if(((a->ls!=NULL)&&(a->ls->val==x))||((a->rs!=NULL)&&(a->rs->val==x))) return a; if(a->val>x) return Delete_Search(x,a->ls); return Delete_Search(x,a->rs); } void Delete(int x){ Node *rt=NULL,*p=NULL,*fa=NULL,*re=NULL; if(root->val==x){ if(root->ls==NULL&&root->rs==NULL){ free(root);root=NULL;return ; }else{ re=root; } }else{ rt=Delete_Search(x,root); if(rt->val>x){ re=rt->ls; if(re->ls==NULL&&re->rs==NULL){free(re);rt->ls=NULL;return ;} }else{ re=rt->rs; if(re->ls==NULL&&re->rs==NULL){free(re);rt->rs=NULL;return ;} } } if(re->ls!=NULL){ p=re->ls; fa=re; if(p->rs==NULL){ fa->ls=p->ls; re->val=p->val; }else{ while(p->rs!=NULL){fa=p;p=p->rs;} fa->rs=p->ls; re->val=p->val; } free(p); }else{ p=re->rs; fa=re; if(p->ls==NULL){ fa->rs=p->rs; re->val=p->val; }else{ while(p->ls!=NULL){fa=p;p=p->ls;} fa->ls=p->rs; re->val=p->val; } free(p); } return ; } void build(int a[],int n){ for(int i=0;i<n;i++) root=Insert(a[i],root); } void show(Node *a){ if(a==NULL) return ; show(a->ls); cout<<a->val<<' '; show(a->rs); }}BSTree;int main(){ srand((unsigned long long)time(0)); int a[13]; cout<<"随机产生插入数据"<<endl; for(int i=0;i<13;i++) a[i]=rand()%97; for(int i=0;i<13;i++) cout<<a[i]<<' '; cout<<endl; cout<<"插入建树"<<endl; BSTree b; b.build(a,13); b.show(b.root); cout<<endl; cout<<"随机查询一个点并用01串表示其路径"<<endl; int temp=rand()%13; cout<<a[temp]<<' '<<b.Search(a[temp],b.root)<<endl; cout<<"删除这个节点"<<endl; b.Delete(a[temp]); b.show(b.root); cout<<endl;}
阅读全文
0 0
- 实验 二叉排序树
- 二叉排序树实验7
- 数据结构--上机实验实验要求:二叉排序树【拓展】
- 实验十六 二叉排序树的建立与查找
- 数据结构实验之查找一:二叉排序树
- 数据结构实验之查找一:二叉排序树
- 数据结构上机实验-二叉排序树的创建
- 数据结构实验之查找一:二叉排序树
- 数据结构实验之查找一:二叉排序树
- SDUT3373数据结构实验之查找一:二叉排序树
- 数据结构实验之查找一:二叉排序树
- 数据结构实验之查找一:二叉排序树
- 数据结构实验之查找一:二叉排序树
- 数据结构实验之查找一:二叉排序树
- SDUTACM 数据结构实验之查找一:二叉排序树
- 数据结构实验之查找一:二叉排序树
- 数据结构实验之查找一:二叉排序树
- 数据结构实验之查找一:二叉排序树
- Java语言中一个字符占几个字节?
- GitHub详解(3)
- 算法分析-快速排序
- Eclipse CDT环境下编写、调试、运行C++程序详谈
- Tmux 入门指南
- 实验 二叉排序树
- android 获取 assets 下的文件
- TCP三次握手和4次分手描述
- 3525:上台阶
- 云大使成长精华指引(全)
- 个人总结:关于c4droid导出apk时的资源填写路径
- Linux 常用命令
- response.setContentType与 request.setCharacterEncoding 区别
- PS制作一个百度的小熊掌LOGO