import java.util.Scanner;
/**
* Created by cq on 2015/8/17 22:22.
* 根据前序序列和中序序列,求后序序列,否则输出No
* 这里没有对输入参数的合法性进行验证,因为合法性由机试系统保证
* 测试例:
8
1 2 4 7 3 5 6 8
4 7 2 1 5 3 8 6
8
1 2 4 7 3 5 6 8
4 1 2 7 5 3 8 6
8
1 2 4 5 3 6 7 8
4 5 2 1 6 3 9 7
* 结果:
7 4 2 5 8 6 3 1
No
5 4 2 6 9 7 3 1
*/
public class Main {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
try {
while (in.hasNextInt()){
int lenOfTree = in.nextInt();
int[] preorder = new int[lenOfTree], inorder = new int[lenOfTree];
for (int i=0; i<lenOfTree; i++){
preorder[i] = in.nextInt();
}
for (int i=0; i<lenOfTree; i++){
inorder[i] = in.nextInt();
}
String result = isBTree(preorder, 0, preorder.length - 1, inorder, 0, inorder.length - 1);
if (result.indexOf("s") != -1){
result = "No";
}
System.out.println(result);
}
}catch (Exception e){}
finally {
in.close();
}
}
public static String isBTree(int[] preorder, int pBegin, int pEnd, int[] inorder, int iBegin, int iEnd){
if (iBegin == iEnd){
return inorder[iBegin]+" ";
}
else if (iBegin > iEnd){
return "";
}
int root = preorder[pBegin], indexOfRoot = indexOf(inorder, iBegin, iEnd, root);
if (indexOfRoot == -1){
return "s";
}
int leftLen = indexOfRoot-iBegin;
return isBTree(preorder, pBegin+1, pBegin+leftLen, inorder, iBegin, indexOfRoot-1)
+ isBTree(preorder, pBegin+leftLen+1, pEnd, inorder, indexOfRoot+1, iEnd) +root+" ";
}
public static int indexOf(int[] arr, int froIndex, int endIndex, int target){
for (int i=froIndex; i<=endIndex; i++){
if (arr[i] == target){
return i;
}
}
return -1;
}
}
华为机试练习150817第二题:求后序序列
最新推荐文章于 2023-07-19 09:48:17 发布