实验 二叉排序树

来源:互联网 发布:吉首大学网络教学 编辑:程序博客网 时间: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;}


原创粉丝点击