-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.java
More file actions
32 lines (30 loc) · 1020 Bytes
/
Solution.java
File metadata and controls
32 lines (30 loc) · 1020 Bytes
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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode buildTree(int[] inorder, int[] postorder) {
return build(inorder, 0, inorder.length - 1, postorder, 0, postorder.length - 1);
}
public TreeNode build(int[] inorder, int inBeg, int inEnd, int[] postorder, int postBeg, int postEnd) {
if (inBeg > inEnd) {
return null;
}
TreeNode root = new TreeNode(postorder[postEnd]);
int pos = -1;
for (int i = inBeg; i <= inEnd; i++) {
if (inorder[i] == postorder[postEnd]) {
pos = i;
break;
}
}
root.left = build(inorder, inBeg, pos - 1, postorder, postBeg, postBeg + (pos - inBeg - 1));
root.right = build(inorder, pos + 1, inEnd, postorder, postBeg + (pos - inBeg), postEnd - 1);
return root;
}
}