给定某二叉树的前序遍历和中序遍历结果,重建该二叉树(不含重复的数字)
例如:
pre = {1, 2, 4, 7, 3, 5, 6, 8}
in = {4, 2, 7, 1 ,5 ,3, 8, 6}
思路:在前序遍历中,第一个数据1是根节点,而在中序遍历中,1左边的3个数据为左子树,右边的4个数据为右子树,因此,在先序遍历中1后边的3个数据为左子树,再向后数4个为右子树。这样可以根据左右子树节点的数量,对每棵特定规模的子树分别递归求解。
public static Map<Integer, Integer> map = new HashMap<>();
//没想到查找数组in中的index位置时可以用到HashMap,好屌哦,用空间换时间, 而且简化了代码
public static TreeNode reConstructBinaryTree(int[] pre, int[] in) {
if (pre == null || pre.length < 1 || in == null || in.length < 1)
return null;
for (int i = 0; i < in.length; i++) {
map.put(in[i], i);
}
return reConstructBinaryTree(pre, 0, pre.length - 1, 0);
}
public static TreeNode reConstructBinaryTree(int[] pre, int preL, int preR, int inL) {
if (preL > preR) {
return null;
}
//构建根结点
TreeNode root = new TreeNode(pre[preL]);
Integer inIndex = map.get(root.val);
//在这里可以插入判断是否包含元素的代码,不包含则错误 (懒)
int leftTreeSize = inIndex - inL;
root.left = reConstructBinaryTree(pre, preL + 1, preL + leftTreeSize, inL);
root.right = reConstructBinaryTree(pre, preL + leftTreeSize + 1, preR, inIndex + 1);
return root;
}
输出的二叉树