题目
通过先序和中序数组生成后序数组
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 + " ");
}
}
}
结果
![1369004-20180416214705434-818380084.png](https://i-blog.csdnimg.cn/blog_migrate/348e087caabcd3c61db607b1fab6459d.png)