已知前序遍历的序号求层次遍历的序号,反之亦然。
#include<cstdio>
#include<cstring>
#include<string.h>
#include<algorithm>
#include<iostream>
#include<math.h>
#include<vector>
using namespace std;
int n,q,k;
int childnum(int r)
{
int x=r;
while(x*2<n)x*=2;
int t=x/r;
return t+((x+t)<n?(t-1):(n-x));
}
void search1(int r,int t)
{
if(t==1)
{
printf("%d\n",r);
return;
}
int c=childnum(r*2)+1;
if(t<=c) search1(r*2,t-1);
else search1(r*2+1,t-c);
}
void search2(int r,int t)
{
if(r==1)
{
printf("%d\n",t);
return;
}
int c=childnum(r/2*2)+1;
if(r&1)search2(r/2,t+c);
else search2(r/2,t+1);
}
int main()
{
scanf("%d%d%d",&n,&q,&k);
if(q==1)search1(1,k);
if(q==2)search2(k,1);
return 0;
}