二叉查找樹模版
僅僅是自己整理的一份模版,怕時間久了會忘掉,主程序裡面是自己做的一些測試,能夠完成輸出查找插入和刪除四種功能,接下來會在這個程序上完成平衡樹Treap的部分功能
#include
#include
#include
#include
#include
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(valuevalue) 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(valuevalue) 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;
}