Construct Binary Tree from Inorder and Postorder Traversal LeetCode solution in Java

1
class Solution {
2
int[] io;
3
int[] po;
4
int n; // nth post order node
5

6
public TreeNode buildTree(int[] inorder, int[] postorder) {
7
this.n = inorder.length - 1;
8
this.io = inorder;
9
this.po = postorder;
10
return buildTree(0, n);
11
}
12

13
public TreeNode buildTree(int low, int high) {
14
if (n < 0 || low > high) return null;
15
int currNode = po[n--];
16
int idxInInorder = low;
17
TreeNode root = new TreeNode(currNode);
18
if (low == high) return root; // no more nodes
19

20
while (io[idxInInorder] != currNode) idxInInorder++; // find index of currNode in inorder
21
root.right = buildTree(idxInInorder + 1, high);
22
root.left = buildTree(low, idxInInorder - 1);
23
return root;
24
}
25
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0