输入:1 3 2 5 6 4 9 8 7 15 12 13 10 11 14
输出:8 4 2 1 3 6 5 7 12 10 9 11 14 13 15
建树与遍历:
#include<iostream>
using namespace std;
const int MAXN=20;
int i,j,n;
struct Node
{
int key,le,ri;
}a[MAXN];
int cmp(const void *a,const void *b){ return (*(Node*)a).key>(*(Node*)b).key?1:-1;}
int treap(int le,int ri)
{
if(le==ri)return le;
int d=(ri+le)/2;
a[d].le=treap(le,(d-1<le?le:d-1));
a[d].ri=treap((d+1>ri?ri:d+1),ri);
return d;
}
void show(int root)
{
if(root==0)return;
else printf("%d ",a[root].key);
show(a[root].le);
show(a[root].ri);
}
int main()
{
//freopen("123.txt","r",stdin);
cin>>n;
for(i=1;i<=n;i++)
cin>>a[i].key;
qsort(a+1,n,sizeof(a[0]),cmp);
int root=treap(1,n);
show(root);
return 0;
}