-
Notifications
You must be signed in to change notification settings - Fork 0
/
106.java
24 lines (17 loc) · 870 Bytes
/
106.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
import java.util.stream.IntStream;
class Solution {
public TreeNode buildTree(int[] inorder, int[] postorder) {
TreeNode tree = null;
int length = inorder.length;
if(length == 1){
return new TreeNode(inorder[0]);
} else if(length == 0){
return null;
}
int root = postorder[length - 1];
int leftIndex = IntStream.range(0, length).filter(i -> root == inorder[i]).findFirst().orElse(-1);
tree = new TreeNode(root, buildTree(Arrays.copyOfRange(inorder, 0, leftIndex), Arrays.copyOfRange(postorder, 0, leftIndex)),
buildTree(Arrays.copyOfRange(inorder, leftIndex + 1, length), Arrays.copyOfRange(postorder, leftIndex, length - 1)));
return tree;
}
}