题目描述
给定某二叉树的前序遍历和中序遍历,请重建出该二叉树并返回它的头结点。
例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建出如下图所示。
提示:
1.0 <= pre.length <= 2000
2.in.length == pre.length
3.0 <= pre[i], in[i] <= 10000
4.pre 和 in 均无重复元素
5.in出现的元素均出现在 pre里
6.只需要返回根结点,系统会自动输出整颗树做答案对比
解题思路
首先,我们需要一个哈希表把中序遍历的值跟下标保存好(为了防止重复遍历in数组,空间换时间),建立一个方法buildTree,我们知道,前序遍历的第一个值就是root,所以通过数组下标查到root的值,并且建立一个root节点,我们还需要知道in数组中,root值的下标,因为root值的左边是左子树的子数组,root值的右边是右子树的子数组,递归的参数是一个难点,首先计算左子树:
第一个参数是pre数组不用说;
第二个节点为前序遍历的左子树的第一个节点就是:preLeft+1;
第三个参数是前序遍历左子树的最后一个节点,又因为pre数组的左子树和右子树的长度等于in数组的左子树和右子树,我们设它为x,则有:
pIndex-1-inLeft == x-(preLeft+1)
x == pIndex-inLeft+preLeft
所以第三个参数为:pIndex-inLeft+preLeft;
第四个参数为map;
第五个参数为中序遍历的左子树的第一个节点也就是:inLeft;
第六个参数为中序遍历的左子树的最后一个节点也就是pIndex-1;
我们知道左子树的计算方法后,右子树的计算方法同理:
第一个参数是pre数组不用说;
第二个节点为前序遍历的右子树的第一个节点,通过前面的计算就是:pIndex-inLeft+preLeft+1;
第三个参数是前序遍历右子树的最后一个节点也就是:preRight;
第四个参数为map;
第五个参数为中序遍历的右子树的第一个节点也就是:pIndex+1;
第六个参数为中序遍历的右子树的最后一个节点也就是inRight;
然后通过递归遍历得到它的左子树和右子树,再将root返回。
代码实现
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
import java.util.HashMap;
import java.util.Map;
public class Solution {
public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
int preLen = pre.length;
int inLen = in.length;
Map<Integer,Integer> map = new HashMap<>();
for(int i = 0;i < in.length;i++) {
map.put(in[i],i);
}
TreeNode root = buildTree(pre,0,preLen-1,map,0,inLen-1);
return root;
}
public TreeNode buildTree(int [] pre,int preLeft,int preRight,
Map<Integer,Integer> map,int inLeft,int inRight) {
if(preLeft > preRight || inLeft > inLeft) return null;
int rootVal = pre[preLeft];
TreeNode root = new TreeNode(rootVal);
int pIndex = map.get(rootVal);
//[preLeft][ ][ preRight]
//[inLeft ][pIndex][ inRight]
//pIndex-1-inLeft == x-(preLeft+1)
//x = pIndex-inLeft+preLeft
root.left = buildTree(pre,preLeft+1,pIndex-inLeft+preLeft,
map,inLeft,pIndex-1);
root.right = buildTree(pre,pIndex-inLeft+preLeft+1,preRight,
map,pIndex+1,inRight);
return root;
}
}