与AVL树操作类似,代码更简单
#include "stdio.h"
#include "stdlib.h"
#include "time.h"
typedef struct _Node{
int data;
int fix;
struct _Node* lf;
struct _Node* rt;
}Node, *pNode;
void l_rot(pNode* root){
pNode t, w = *root;
t = w->rt;
w->rt = t->lf;
t->lf = w;
*root = t;
}
void r_rot(pNode* root){
pNode t, w = *root;
t = w->lf;
w->lf = t->lf;
t->lf = w;
*root = t;
}
void insert(pNode* root, int val){
pNode w = *root;
if(!w){
w = (pNode)malloc(sizeof(Node));
w->data = val;
w->fix = rand()%100;
w->lf = w->rt = 0;
*root = w;
return;
}
if(val > w->data){
insert(&(w->rt), val);
if(w->rt->fix < w->fix)
l_rot(root);
}
else{
insert(&(w->lf), val);
if(w->lf->fix < w->fix)
r_rot(root);
}
}
void remove(pNode* root, int val){
pNode w = *root;
if(!w) return;
if(val == w->data){
if(!(w->lf) || !(w->rt)){
*root = w->lf ? w->lf : w->rt;
free(w);
return;
}
if(w->lf->fix < w->lf->fix){
r_rot(&w);
remove(&(w->rt), val);
}
else{
l_rot(&w);
remove(&(w->lf), val);
}
*root = w; //!!!
}else if(val > w->data)
remove(&((*root)->rt), val);
else
remove(&((*root)->lf), val);
}
void show(pNode root){
if(!root) return;
printf("%d ", root->data);
show(root->lf);
show(root->rt);
}
void main(){
int i;
pNode root = 0;
srand(time(0));
for(i=0; i<10; i++)
insert(&root, i);
show(root); printf("\n");
remove(&root, 5);
show(root); printf("\n");
remove(&root, 7);
show(root); printf("\n");
}