题目传送门:https://www.patest.cn/contests/gplt/L2-006
题目大意:给一个树的中序遍历的结果和后序遍历的结果让你求层序遍历的结果。
题目分析:用中序遍历和后序遍历的结果将树建起来,再进行层序遍历。更加具体地:使用递归的方法,每次后序遍历的时候都可以找到一个根节点,通过这个根节点在中序遍历将树分为左子树、根节点、右子树三个部分。递归执行此操作即可建树。再遍历一次tree数组就可以输出层序遍历的结果。
import java.util.Scanner;
public class Main{
static Scanner input = new Scanner(System.in);
static int at; //后序遍历(递归)到哪
static int[] hou; //从1开始存储后序遍历序列
static int[] zhong; //从1开始存储中序遍历序列
static int[] tree;
public static void main(String[] args){
int count = input.nextInt();
tree = new int[count<<9|1];//这个地方非要开到这么大的数组才能过得了全部的样例
at = count;
hou = new int[count+1];
zhong = new int[count+1];
for(int i=1;i<=count;i++){
hou[i] = input.nextInt();
}
for(int i=1;i<=count;i++){
zhong[i] = input.nextInt();
}
//建树
BuildTree(1,count,findindex(zhong,hou[hou.length-1]));
boolean judge = true;
for(int i=0;i<=tree.length-1;i++){
if(tree[i]!=0&&judge){
System.out.print(tree[i]);
judge = false;
continue;
}
if(tree[i]!=0&&!judge)System.out.print(" "+tree[i]);
}
}
static void BuildTree(int l,int r,int root){
//l代表在中序遍历中的左地址界限,r是右地址界限
tree[root] = hou[at];
int index = findindex(zhong,hou[at]);//index是该子树的根节点在中序遍历中的地址;
at--;
if(r>index) BuildTree(index+1,r,2*root+1);
if(l<index) BuildTree(l,index-1,2*root-1);
}
static int findindex(int temp[],int find){
for(int i=1;i<=temp.length-1;i++){
if(temp[i]==find)return i;
}
return -1;
}
}
一道接近一样的题目:前序中序求反转层序
链接:https://www.patest.cn/contests/gplt/L2-011
import java.util.Scanner;
public class Main{
static Scanner input = new Scanner(System.in);
static int[] zhong;
static int[] qian;
static int pointer = 1;
static int[] tree;
public static void main(String[] args){
int count = input.nextInt();
zhong = new int[count+1];
qian = new int[count+1];
tree = new int[count<<10|1];
for(int i=1;i<=count;i++){
zhong[i] = input.nextInt();
}
for(int i=1;i<=count;i++){
qian[i] = input.nextInt();
}
BuildTree(1,count,IndexFinder(zhong,qian[1]));
boolean stop = false;
boolean judge = true;
for(int i=1;;i++){
for(int j=(int) (Math.pow(2, i)-1);j>=Math.pow(2, i-1);j--){
if(j>=tree.length){stop = true;break;}
if(tree[j]!=0&&judge){
System.out.print(tree[j]);
judge = false;
continue;
}
if(tree[j]!=0&&!judge){
System.out.print(" "+tree[j]);
}
}
if(stop)break;
}
}
static void BuildTree(int l,int r,int root){
tree[root] = qian[pointer];
int index = IndexFinder(zhong,tree[root]);
pointer++;
if(l<index) BuildTree(l,index-1,2*root);
if(index<r) BuildTree(index+1,r,2*root+1);
}
static int IndexFinder(int[] data,int find){
for(int i=1;i<=data.length-1;i++){
if(find==data[i])return i;
}
return -1;
}
}