class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
public class Solution {
public static TreeNode reConstructBinaryTree(int[] pre, int[] in) {
return constructCore(pre, 0, pre.length - 1, in, 0, in.length - 1);
}
/**
*
* @param pre 前序遍历
* @param i 前序首下标
* @param j 前序尾下标
* @param in 中序遍历
* @param k 中序遍历首下标
* @param l 中序遍历尾下标
* @return
*/
public static TreeNode constructCore(int[] pre, int i, int j, int[] in, int k, int l) {
if (k > l) {
return null;
//终止条件
} else {
TreeNode root = new TreeNode(pre[i]);
//构建子树节点
for (int e = k; e <= l; e++) {
if (in[e] == pre[i]) {
//找到根了
System.out.print(e);
//e-k 左子熟长度 e-k+i 左子熟终点
//k 左子熟起点 e-1 左子熟重点
root.left = constructCore(pre, i + 1, i + e - k, in, k, e - 1);
//e-k+i 左子熟终点 e-k+i+1 柚子树起点
//e+1 柚子树起点 l柚子树终点
root.right = constructCore(pre, e - k + i + 1, j, in, e + 1, l);
//递归建立二叉树
}
}
System.out.println();
return root;
}
}
}
【剑指offer】重建二叉树
最新推荐文章于 2020-03-07 17:13:55 发布