面试题6-重建二叉树

题目

输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。

解题

因为二叉树前序和中序遍历都有它的规律(在二叉树的前序遍历序列中,第一个数字总是树的根结点的值。在中序遍历序列中,根结点的值在序列的中间, 左子树的结点的值位于根结点的值的左边,而右子树的结点的值位于根结点的值的右边。),通过实例分析一下就可以找到。结合前序和中序遍历就可以找到二叉树的根结点和左右支。

而左支和右支的解决办法和圆二叉树相同,因而可以用递归的方法。

这道题思路还是出挺快的,但是自己就卡在了因为数据长度不可变而引起的一些bug上。我的代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
// 排除非法输入
if (pre == null || in == null || pre.length != in.length){
return null;
}
// 这里要特别注意!!!
// 因为数组的不可变长的特性,下面在根据根结点创建存放左右支的时候,
// 若不存在左右支了,则可能创建长度为0的数组,不能用=null来判断,要用数组长度来判断
if (in.length == 0 || pre.length == 0 ){
return null;
}
TreeNode root = new TreeNode(pre[0]);
int rootIndex = 0;
int length = pre.length;
// 找到跟结点在中序遍历中的位置
for (int i=0; i<=length-1;i++){
if (in[i] == pre[0]){
rootIndex = i;
break;
}
}
// 根据节点位置,创建相应大小的数组存放根结点的左支和右支
int[] leftPre = new int [rootIndex];
int[] leftIn = new int [rootIndex];
int[] rightPre = new int [length-rootIndex-1];
int[] rightIn = new int [length-rootIndex-1];
// 遍历存放
for (int i=0; i<=length-1;i++){
if (i < rootIndex){
leftPre[i] = pre[i+1];
leftIn[i] = in[i];
} else if (i > rootIndex){
rightPre[i-1-rootIndex] = pre[i];
rightIn[i-1-rootIndex] = in[i];
}
}
// 递归,求左支&右支的根节点, and so on ..
root.left = reConstructBinaryTree(leftPre, leftIn);
root.right = reConstructBinaryTree(rightPre, rightIn);
return root;
}
}

牛客网上别人更高效的代码:(使用了Arrays.copyOfRange()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
import java.util.Arrays;
public class Solution {
public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
if (pre.length == 0 || in.length == 0) {
return null;
}
TreeNode root = new TreeNode(pre[0]);
// 在中序中找到前序的根
for (int i = 0; i < in.length; i++) {
if (in[i] == pre[0]) {
// 左子树,注意 copyOfRange 函数,左闭右开
root.left = reConstructBinaryTree(Arrays.copyOfRange(pre, 1, i + 1), Arrays.copyOfRange(in, 0, i));
// 右子树,注意 copyOfRange 函数,左闭右开
root.right = reConstructBinaryTree(Arrays.copyOfRange(pre, i + 1, pre.length), Arrays.copyOfRange(in, i + 1, in.length));
break;
}
}
return root;
}
}

总结

  1. Arrays.copyOfRange()方法

copyOfRange是输入java.util包中的Arrays类的静态内部方法,可以被类直接调用。

1
Arrays.copyOfRange(T[ ] original,int from,int to)

将一个原始的数组original,从下标from开始复制,复制到上标to,生成一个新的数组。

  1. int[] myArray = new int[0];表示指向一个空的数组,而不是指向null。

References

牛客网讨论与题解

《剑指offer》

Java.util中的Arrays.copyOfRange方法的用法

[Why is int] a = new int[0]; allowed?