-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLC_105.java
48 lines (41 loc) · 1.55 KB
/
LC_105.java
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
import java.util.Arrays;
public class LC_105 {
public static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {
}
TreeNode(int val) {
this.val = val;
}
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
public TreeNode buildTree(int[] preorder, int[] inorder) {
return build(preorder, inorder);
}
//该方法时间复杂度比较大
public static TreeNode build(int[] preorder, int[] inorder) {
if (preorder == null || inorder == null || preorder.length == 0 || inorder.length == 0) return null;
int rootVal = preorder[0];
int rootInorderIdx = findRootInorderIdx(rootVal, inorder);
TreeNode root = new TreeNode(rootVal);
int[] inorderLeft = Arrays.copyOfRange(inorder, 0, rootInorderIdx);
int[] inorderRight = Arrays.copyOfRange(inorder, rootInorderIdx + 1, inorder.length);
int[] preorderLeft = Arrays.copyOfRange(preorder, 1, 1 + inorderLeft.length);
int[] preorderRight = Arrays.copyOfRange(preorder, 1 + inorderLeft.length, preorder.length);
root.left = build(preorderLeft, inorderLeft);
root.right = build(preorderRight, inorderRight);
return root;
}
public static int findRootInorderIdx(int val, int[] inorder) {
for (int i = 0; i < inorder.length; i++) {
if (inorder[i] == val) return i;
}
return -1;
}
}