二叉查找树模版

不过自己整理的一份模版。怕时间久了会忘掉。主程序里面是自己做的一些測试。可以完毕输出查找插入和删除四种功能。接下来会在这个程序上完毕平衡树Treap的部分功能
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long ll;
const int inf=0x3f3f3f3f;
const int maxn=100010;
struct Treap_Node{
    Treap_Node *left,*right;
    int value;
};
Treap_Node *root;
void Treap_Print(Treap_Node *P){//从小到大输出
    if(P){
        Treap_Print(P->left);
        printf("%d\n",P->value);
        Treap_Print(P->right);
    }
}
int Treap_Find(Treap_Node *P,int value){//查找有没有value这个数
    if(!P) return 0;
    if(P->value==value) return 1;
    else if(value<P->value) return Treap_Find(P->left,value);
    else return Treap_Find(P->right,value);
}
void Treap_Insert(Treap_Node *&P,int value){//插入一个数
    if(!P){
        P=new Treap_Node;
        P->left=P->right=NULL;//左右儿子均为空
        P->value=value;
    }
    else if(value<=P->value) Treap_Insert(P->left,value);
    else Treap_Insert(P->right,value);
}
int Find_Delete(Treap_Node *&P){
    if(!P->left){
        Treap_Node *t=P;
        int r=P->value;
        P=P->right;
        delete t;
        return r;
    }else return Find_Delete(P->left);
}
void Treap_Delete(Treap_Node *&P,int value){//删除一个数
    if(!P) return ;
    if(P->value==value){
        if(P->left&&P->right) P->value=Find_Delete(P->right);
        else{
            Treap_Node *t=P;
            if(P->left) P=P->left;
            else P=P->right;
            delete t;
        }
    }else if(value<P->value) Treap_Delete(P->left,value);
    else Treap_Delete(P->right,value);
}
int main(){
    int m,a;
    char ch;
    while(scanf("%d",&m)!=-1){
        root=NULL;
        Treap_Insert(root,2);
        Treap_Insert(root,3);
        Treap_Insert(root,1);
        Treap_Print(root);
        while(m--){
            getchar();
            scanf("%c",&ch);
            if(ch=='F'){
            scanf("%d",&a);
            int t=Treap_Find(root,a);
            if(t) printf("Found\n");
            else printf("Not Found\n");
            }else if(ch=='I'){
                scanf("%d",&a);
                Treap_Insert(root,a);
            }else if(ch=='P'){
                Treap_Print(root);
            }else if(ch=='D'){
                scanf("%d",&a);
                Treap_Delete(root,a);
            }
        }
    }
    return 0;
}

posted on 2017-07-18 18:36  blfbuaa  阅读(113)  评论(0编辑  收藏  举报