我们首先把这棵树给建出来(就和建二叉搜索树一个建法)
然后记录好当前节点的值,左儿子和右儿子之后,我们开一个堆
首先把根扔进去,每次取出最小的节点,输出并把这个节点的左右儿子扔进堆里(如果没有左儿子或右儿子那就不用push了)
最后输出的n个节点就是答案了
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <iostream>
#include <ctime>
#include <map>
#include <queue>
#include <cstdlib>
#include <string>
#include <climits>
#include <set>
#include <vector>
using namespace std;
inline int read(){
int k=0,f=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){k=k*10+ch-'0';ch=getchar();}
return k*f;
}
struct ppap{int x,ls,rs;}a[100010];
bool operator <(ppap a,ppap b){return a.x>b.x;}
priority_queue<ppap>q;
int n,rt,cnt=0;
inline void insert(int x){
if(!rt){rt=++cnt;a[rt].x=x;return;}
int now=rt,p;
while(now){
p=now;
if(x<a[now].x)now=a[now].ls;
else now=a[now].rs;
}
if(x<a[p].x)a[p].ls=++cnt;
else a[p].rs=++cnt;
a[cnt].x=x;
}
int main()
{
n=read();
for(int i=1;i<=n;i++){
int x=read();
insert(x);
}
q.push(a[rt]);
for(int i=1;i<=n;i++){
ppap now=q.top();q.pop();
printf("%d ",now.x);
if(now.ls)q.push(a[now.ls]);
if(now.rs)q.push(a[now.rs]);
}
return 0;
}