//BST
#include<stdio.h>
#include<stdlib.h>
struct node{
int x;
struct node *left,*right;
};
struct node *h,*p,*q;
void insert(int s,struct node *t){
if(s>t->x){
if(t->right==NULL){
q=new node;
q->x=s;q->left=NULL;q->right=NULL;
t->right=q;
}else insert(s,t->right);
}else{
if(t->left==NULL){
q=new node;
q->x=s;q->left=NULL;q->right=NULL;
t->left=q;
}else insert(s,t->left);
}
}
void dfs(struct node *t){
if(t==NULL)return;
dfs(t->left);
printf("%d ",t->x);
dfs(t->right);
}
int main(){
int i,j,k,m,n;
scanf("%d",&n);
scanf("%d",&k);
h=new node;
h->x=k;h->left=NULL;h->right=NULL;
for(i=2;i<=n;i++){
scanf("%d",&k);
insert(k,h);
}
dfs(h);
system("pause");
return 0;
}
//TREAP
#include<iostream>
#include<cstdio>
#include<cstdlib>
using namespace std;
struct node{
int x,w;
struct node *h,*r,*l;
node(){
x=0;w=0;h=r=l=NULL;
}
};
node *root;
void zrg(node *u,node *v){
node *t=u->h;
u->l=v->r;if(v->r!=NULL)v->r->h=u;
u->h=v;v->r=u;
v->h=t;
if(t!=NULL){
if(t->l==u)t->l=v;
else t->r=v;
}else root=v;
}
void zlg(node *u,node *v){
node *t=u->h;
u->r=v->l;if(v->l!=NULL)v->l->h=u;
v->l=u;u->h=v;
v->h=t;
if(t!=NULL){
if(t->l==u)t->l=v;
else t->r=v;
}else root=v;
}
void out(node *u){
if(u!=NULL){
out(u->l);
printf("%d ",u->x);
out(u->r);
}
}
void insert(node *u,node *v){
if(u==NULL)return;
if(v->x>u->x){
if(u->r==NULL){
u->r=v;v->h=u;
while(v->h!=NULL && v->w<v->h->w){
if(v==v->h->r)zlg(v->h,v);
else zrg(v->h,v);
}
}else insert(u->r,v);
}else{
if(u->l==NULL){
u->l=v;v->h=u;
while(v->h!=NULL && v->w<v->h->w){
if(v==v->h->r)zlg(v->h,v);
else zrg(v->h,v);
}
}else insert(u->l,v);
}
}
int main(){
int i,j,k,m,n,t;
node *p,*q;
cin>>n;
cin>>k;
srand(3433);
root=new node;
root->x=k;root->w=rand();
for(i=2;i<=n;i++){
cin>>k;
q=new node;
q->x=k;q->w=rand();
insert(root,q);
}
out(root);
return 0;
}
BST && TREAP 实现简单排序
最新推荐文章于 2022-07-20 23:38:32 发布