題目
經過先序和中序數組生成後序數組
java代碼
package com.lizhouwei.chapter3;
import java.util.HashMap;
import java.util.Map;
/**
* @Description:經過先序和中序數組生成後序數組
* @Author: lizhouwei
* @CreateDate: 2018/4/16 21:21
* @Modify by:
* @ModifyDate:
*/
public class Chapter3_22 {
public int[] getPosArray(int[] pre, int[] in) {
if (pre == null || in == null) {
return null;
}
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < in.length; i++) {
map.put(in[i], i);
}
int[] pos = new int[in.length];
preAndIn(pre, 0, pre.length - 1, in, 0, in.length - 1, pos, pos.length - 1, map);
return pos;
}
public int preAndIn(int[] pre, int preStart, int preEnd, int[] in, int inStart, int inEnd, int[] pos, int posEnd, Map<Integer, Integer> map) {
if (preStart > preEnd) {
return posEnd;
}
int vlaue = pre[preStart];
pos[posEnd--] = vlaue;
int index = map.get(vlaue);
posEnd = preAndIn(pre, preStart + index - inStart + 1, preEnd, in, index + 1, inEnd, pos, posEnd, map);
posEnd = preAndIn(pre, preStart + 1, preStart + index - inStart, in, inStart, index - 1, pos, posEnd, map);
return posEnd;
}
//測試
public static void main(String[] args) {
Chapter3_22 chapter = new Chapter3_22();
int[] pre = {5, 2, 1, 3, 4, 8, 6, 7, 9, 10};
int[] in = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int[] pos = chapter.getPosArray(pre, in);
System.out.println("前序數組:pre = {5, 2, 1, 3, 4, 8, 6, 7, 9, 10}");
System.out.println("中序數組:in = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}");
System.out.println("後序數組:pos = {1, 4, 3, 2, 7, 6, 10, 9, 8, 5}");
System.out.println();
System.out.print("前序和中序組成後序:");
for (int i : pos) {
System.out.print(i + " ");
}
}
}
結果