-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConstructBinaryTreePreorderInorder_105.java
More file actions
50 lines (42 loc) · 1.52 KB
/
ConstructBinaryTreePreorderInorder_105.java
File metadata and controls
50 lines (42 loc) · 1.52 KB
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
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
/**
* Recursion:
* - Inorder + Preorder/Postorder/Level order can recover a binary tree
* - Other combinations can not
* - Inorder must be included to decide left/right subtrees
* - The other order is used to determine the root
*/
public class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
return buildTree(preorder, 0, preorder.length-1,
inorder, 0, inorder.length-1);
}
private TreeNode buildTree(int[] preorder, int prestart, int preend,
int[] inorder, int instart, int inend) {
if (preend < prestart) return null;
TreeNode root = new TreeNode(preorder[prestart]);
int rootindex = instart; // find root index in inorder
for(; rootindex<=inend; rootindex++)
if(inorder[rootindex] == preorder[prestart])
break;
int leftlength = rootindex - instart;
TreeNode left = buildTree(preorder, prestart+1, prestart+leftlength,
inorder, instart, rootindex-1);
TreeNode right = buildTree(preorder, prestart+leftlength+1, preend,
inorder, rootindex+1, inend);
root.left = left;
root.right = right;
return root;
}
}
/**
* Iteratively?
*/