import java.util.Scanner;
/**
* @PackageName: PACKAGE_NAME
* @ClassName: Main
* @Author: fan
* @Date: 2019/12/13 14:02
* @Description:
*/
//二叉树已知后续和中序数列,求前序数列
public class Main {
static int arrfirst[] = new int[30];
static int point = 0;
public static void getArrfirst(int arrl[],int arrm[]){
//获取根节点
if (arrl.length == 0 )return;
int root = arrl[arrl.length-1];
arrfirst[point++]= root;
if (arrl.length == 1)return;
int rootindex=0;
for (int i = 0; i < arrm.length; i++) {
if (root == arrm[i]){
rootindex = i;
break;
}
}
int arrleft[] = new int[rootindex];
int arrright[] = new int[arrm.length-rootindex-1];
for (int i = 0; i < arrm.length; i++) {
if (i < rootindex){
arrleft[i] = arrm[i];
}else if(i > rootindex){
arrright[i-1-rootindex] = arrm[i];
}
}
int arrLl[] = new int[rootindex];
int arrRl[] = new int[arrm.length-rootindex-1];
int j = 0;
for (int i = 0; i < arrLl.length; i++) {
arrLl[i] = arrl[j++];
}
for (int i = 0; i < arrRl.length; i++) {
arrRl[i] = arrl[j++];
}
getArrfirst(arrLl,arrleft);
getArrfirst(arrRl,arrright);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int length = sc.nextInt();
int arrlast[] = new int[length];
int arrmid[] = new int[length];
for (int i = 0; i < arrlast.length; i++) {
arrlast[i] = sc.nextInt();
}
for (int i = 0; i < arrmid.length; i++) {
arrmid[i] = sc.nextInt();
}
getArrfirst(arrlast,arrmid);
System.out.print("Preorder:");
for (int i = 0; i <length; i++) {
System.out.print(arrfirst[i]);
if (i!=length)System.out.print(" ");
}
}
}
输入样例:
7
2 3 1 5 7 6 4
1 2 3 4 5 6 7
输出样例:
Preorder: 4 1 3 2 6 5 7
通过一个二叉树的后序,中序遍历求出前序遍历
最新推荐文章于 2022-07-17 23:00:27 发布