题意:给定一棵二叉排序树的中序转换为前序的逆序输出
思路:后序遍历找到根,再在中序遍历的相应位置找到分成的两棵子树,依次进行遍历。
#include <stdio.h>
#include <algorithm>
#include <iostream>
using namespace std;
#define MAX 3002
int pos[MAX];
int a[MAX];
int out[MAX];
int n,c;
int find(int x){
for(int i=0;i<n;i++)
if(x==a[i])
return i;
return -1;
}
//s,e为中序的起点、终点,ss,ee为后序的起点、终点
void build(int s,int e,int ss,int ee){
if(s>e||ss>ee) return;
int root=find(pos[ee]);
out[c++]=pos[ee];
build(s,root-1,ss,ss+root-s-1);
build(root+1,e,ss+root-s,ee-1);
}
int main(){
scanf("%d",&n);
for(int i=0;i<n;i++){
scanf("%d",&pos[i]);
a[i]=pos[i];
}
sort(a,a+n);
build(0,n-1,0,n-1);
for(int i=n-1;i>0;i--)
printf("%d ",out[i]);
printf("%d\n",out[0]);
return 0;
}
/*测试:
Sample Input
9
1 7 5 21 22 27 25 20 10
Sample Output
27 21 22 25 20 7 1 5 10
*/