http://hzwer.com/5790.html 代码
http://www.cppblog.com/MatoNo1/archive/2013/03/03/192131.html //原理讲解
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int n,top,root;
int ls[105],rs[105],fa[105],ans[105];
void solve(){
int x=root;
while(rs[x]!=-1) x=ls[x];
int t=ls[x];
if(t!=-1&&ls[t]==-1&&rs[t]==-1) x=t;
ans[++top]=x;
if(x==root) root=ls[root];
int f=fa[x];
if(f!=-1) ls[f]=ls[x],fa[ls[f]]=f;
while(f!=-1) swap(ls[f],rs[f]),f=fa[f];
}
int main(){
fa[0]=-1;
memset(ls,-1,sizeof(ls));
memset(rs,-1,sizeof(rs));
scanf("%d",&n);
for(int i=1;i<=n;++i) {
int x;scanf("%d",&x);
if(x<100) ls[x]=i,fa[i]=x;
else rs[x-100]=i,fa[i]=x-100;
}
for(int i=1;i<=n+1;++i)
solve();
while(top) printf("%d ",ans[top--]);
}