Construct Binary Tree from Preorder and Inorder Traversal

题目大意

  https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/

  从前序和中序序列构建一棵树

题目分析

  递归即可,这里用了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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
if (preorder == null || inorder == null) {
return null;
}
if(preorder.length == 0 || inorder.length == 0 || preorder.length != inorder.length) {
return null;
}
int first = preorder[0];
int loc = -1;
for(int i = 0; i < inorder.length; i++) {
if(inorder[i] == first) {
loc = i;
break;
}
}
int[] newIn1 = new int[0];
if(0 < loc) {
newIn1 = Arrays.copyOfRange(inorder, 0, loc);
}
int[] newPre1 = new int[0];
if(loc > 0 && loc + 1 <= preorder.length) {
newPre1 = Arrays.copyOfRange(preorder, 1, loc + 1);
}
TreeNode left = buildTree(newPre1, newIn1);
int[] newIn2 = new int[0];
int[] newPre2 = new int[0];
if(loc + 1 < inorder.length) {
newIn2 = Arrays.copyOfRange(inorder, loc + 1, inorder.length);
newPre2 = Arrays.copyOfRange(preorder, loc + 1, preorder.length);
}
TreeNode right = buildTree(newPre2, newIn2);
TreeNode ret = new TreeNode(first);
ret.left = left;
ret.right = right;
return ret;
}
}