-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSolution.java
More file actions
31 lines (26 loc) · 771 Bytes
/
Copy pathSolution.java
File metadata and controls
31 lines (26 loc) · 771 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
import Solution.TreeNode;
public class Solution
{
private int postOrderIdx;
public TreeNode buildTree(int[] inorder, int[] postorder)
{
postOrderIdx = postorder.length - 1;
return getRoot(inorder, postorder, 0, inorder.length - 1);
}
private TreeNode getRoot(int[] inorder, int[] postorder, int start, int end)
{
if (start > end)
{
return null;
}
TreeNode root = new TreeNode(postorder[postOrderIdx--]);
int rootIdx = 0;
while (inorder[rootIdx] != root.val)
{
rootIdx++;
}
root.right = getRoot(inorder, postorder, rootIdx + 1, end);
root.left = getRoot(inorder, postorder, start, rootIdx - 1);
return root;
}
}