重建二叉树
题目描述
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。 |
思路1
- 在二叉树的前序遍历序列中,第一个数字老是树的根节点的值。但在中序遍历序列中,根节点的值在序列的中间,左子树的节点值位于根节点的值的左边,而右子树的节点的值位于根节点的值的右边。
- 例如:
前序序列{1,2,4,7,3,5,6,8} = pre
中序序列{4,7,2,1,5,3,8,6} = in
- 根据当前前序序列的第一个结点肯定根结点,为 1;
- 找到 1 在中序遍历序列中的位置,为 in[3];
- 切割左右子树,则 in[3] 前面的为左子树, in[3] 后面的为右子树;
- 则切割后的左子树前序序列为:{2,4,7},切割后的左子树中序序列为:{4,7,2};切割后的右子树前序序列为:{3,5,6,8},切割后的右子树中序序列为:{5,3,8,6};
- 对子树分别使用一样的方法分解。
程序(java)
/**
* code1:递归(传入数组的拷贝)
* 时间复杂度:O(n),空间复杂度:O(n)
*/
import java.util.Arrays;
public static TreeNode reConstructBinaryTree(int[] pre, int[] in) {
if (pre == null || in == null || pre.length == 0 || in.length == 0) {
return null;
}
if (pre.length != in.length) {
return null;
}
TreeNode root = new TreeNode(pre[0]);
for (int i = 0; i < pre.length; i++) {
if (pre[0] == in[i]) {
root.left = reConstructBinaryTree(Arrays.copyOfRange(pre, 1, i + 1), Arrays.copyOfRange(in, 0, i));
root.right = reConstructBinaryTree(Arrays.copyOfRange(pre, i + 1, pre.length), Arrays.copyOfRange(in, i + 1, in.length));
}
}
return root;
}
复制代码
/**
* code2:递归(传入子数组的边界索引)
* 时间复杂度:O(n),空间复杂度:O(n)
*/
public class Solution {
public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
if (pre == null || pre.length == 0 ||
in == null || in.length == 0) return null;
return helper(pre, 0, pre.length - 1, in, 0, in.length - 1);
}
private TreeNode helper(int[] pre, int preL, int preR, int[] in, int inL, int inR) {
if (preL > preR || inL > inR) {
return null;
}
int rootVal = pre[preL];
int index = 0;
while (index <= inR && in[index] != rootVal) {
index++;
}
TreeNode root = new TreeNode(rootVal);
root.left = helper(pre, preL + 1, preL - inL + index, in, inL, index);
root.right = helper(pre, preL - inL + index + 1, preR, in, index + 1, inR);
return root;
}
}
复制代码
补充
关于Java中的Arrays.copyOfRange()方法
- 要使用这个方法,首先要import java.util.Arrays;
- 将一个原始的数组original,从下标from开始复制,复制到上标to,生成一个新的数组(8大类型基本数组)。注意这里包括下标from,不包括上标to。
Arrays.copyOfRange(T[ ] original,int from,int to)
复制代码
- 实例:
int [] s1 = {1,2,3,4,5};
int [] s2 = Arrays.copyOfRange(s1, 2, 4);
System.out.println(Arrays.toString(s2));
复制代码
输出 [3,4]
复制代码
int [] s1 = {1,2,3,4,5};
int [] s2 = Arrays.copyOfRange(s1, 2, 5);
System.out.println(Arrays.toString(s2));
复制代码
输出 [3,4,5]
复制代码
int [] s1 = {1,2,3,4,5};
int [] s2 = Arrays.copyOfRange(s1, 2, 2);
System.out.println(Arrays.toString(s2));
复制代码
输出 []
复制代码
int [] s1 = {1,2,3,4,5};
int [] s2 = Arrays.copyOfRange(s1, 5, 5);
System.out.println(Arrays.toString(s2));
复制代码
输出 []
复制代码
參考
- 数据结构之二叉树
- 重建二叉树(牛客网)
- 重建二叉树(GitHub)