https://www.cnblogs.com/googlemeoften/p/5853280.html
题目:给定二叉树的前序遍历和中序遍历,生成二叉树。
Example:
前序遍历数组:preArr[]:{1,2,4,5,3,6,7}
中序遍历数组:inArr[]:{4,2,5,1,6,3,7}
生成的二叉树如下图:
解题思路:
由二叉树的前序变量性质可知:preArr[0] 是数组的根节点,有根据二叉树的中序遍历的性质可知,{4,2,5}是二叉树的左子树,{6,3,7}在右子树上,重复执行该操作就构造出了二叉树
package com.algorithm;
import org.junit.Test;
import java.util.Arrays;
/**
* Author: zhaoxiaohui03
* Date: 2019/3/25 15:50
* Email:
* Desc: 二叉树:根据先序中序二叉数数组,生成后序二叉树数组
*/
public class BinaryTreePostBasePreMid {
@Test
public void test() {
// int[] preArr = {1, 2, 4, 5, 3, 6, 7};
int[] preArr = {1, 2, 4};
//int[] midArr = {4, 2, 5, 1, 6, 3, 7};
int[] midArr = {1, 2, 4};
int[] postArr = new int[midArr.length];
analysis(preArr, 0, preArr.length - 1, midArr, 0, midArr.length - 1, postArr, 0, postArr.length - 1);
System.out.println(Arrays.toString(postArr));
}
private void analysis(int[] preArr, int prestart, int preend, int[] midArr, int midstart, int midend, int[] postArr, int poststart, int postend) {
if (prestart > preArr.length - 1
|| postend < 0 || prestart > preend || midstart > midend || poststart > postend) {
return;
}
/*前序数组中,第一个一定是根节点;且后续中最后一个元素也一定是根节点*/
int root = preArr[prestart];
postArr[postend] = root;
/*求出根节点在中序中的位置i,那么在中序中,<i的都是根节点左子树的,>i的都是根节点右子树的*/
int i;
for (i = midstart; i <= midend; i++) {
if (midArr[i] == root) {
break;
}
}
int leftSize = i - midstart;
int rightSize = midend - i;
/*左子树*/
analysis(preArr, prestart + 1, prestart + leftSize,
midArr, midstart, i - 1,
postArr, poststart, poststart + leftSize - 1);
/*右子树*/
analysis(preArr, prestart + 1 + leftSize, preend,
midArr, i + 1, midend,
postArr, poststart + leftSize, postend - 1);
}
}