BST && TREAP 实现简单排序

来源:互联网 发布:看图识番号软件下载 编辑:程序博客网 时间:2024/06/03 15:02
//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;}elseinsert(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<stdio.h>#include<stdlib.h>struct node{int v,w;struct node *h,*l,*r;};struct node *s,*p,*q;void rrotate(struct node *A,struct node *B){A->h=B->h;if(A->h!=NULL)    if(A->h->l==B)A->h->l=A;    else A->h->r=A;B->l=A->r;if(A->r!=NULL)A->r->h=B;B->h=A;A->r=B;}void lrotate(struct node *A,struct node *B){A->h=B->h;if(A->h!=NULL)    if(A->h->l==B)A->h->l=A;    else A->h->r=A;B->r=A->l;    if(A->l!=NULL)A->l->h=B;B->h=A;A->l=B;}void insert(struct node *t,int x){if(t==NULL)return ;if(x<t->v){if(t->l==NULL){q=new node;q->v=x;q->w=rand()%100;q->h=t;q->l=NULL;q->r=NULL;t->l=q;p=q;while(p->h!=NULL && p->w<p->h->w){if(p->h->l==p)rrotate(p,p->h);elselrotate(p,p->h);if(p->h==NULL)s=p;}}elseinsert(t->l,x);}else{if(t->r==NULL){q=new node;q->v=x;q->w=rand()%100;q->h=t;q->l=NULL;q->r=NULL;t->r=q;p=q;while(p->h!=NULL && p->w<p->h->w){if(p->h->l==p)rrotate(p,p->h);elselrotate(p,p->h);if(p->h==NULL)s=p;}}elseinsert(t->r,x);}}void dfs(struct node *t){if(t==NULL)return;dfs(t->l);printf("%d ",t->v);dfs(t->r);}int main(){int i,j,k,m,n;srand(1235);scanf("%d",&n);scanf("%d",&k);s=new node;s->v=k;s->w=rand()%100;s->h=NULL;s->l=NULL;s->r=NULL;for(i=2;i<=n;i++){scanf("%d",&k);insert(s,k);}dfs(s);system("pause");return 0;}

1 0