Skip to content

Commit c3c0628

Browse files
Merge pull request neetcode-gh#333 from spartan218/main
[java][105] Add solution without using Array.copyOfRange()
2 parents 7213a63 + 04c8b79 commit c3c0628

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

java/105-Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal.java

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,3 +29,33 @@ public TreeNode buildTree(int[] preorder, int[] inorder) {
2929
return root;
3030
}
3131
}
32+
33+
// Solution without using Array copies
34+
class Solution {
35+
36+
Map<Integer, Integer> inorderPositions = new HashMap<>();
37+
38+
public TreeNode buildTree(int[] preorder, int[] inorder) {
39+
if(preorder.length < 1 || inorder.length < 1) return null;
40+
41+
for(int i = 0; i < inorder.length; i ++) {
42+
inorderPositions.put(inorder[i], i);
43+
}
44+
45+
return builder(preorder, 0, 0, inorder.length-1);
46+
}
47+
48+
public TreeNode builder(int[] preorder, int preorderIndex, int inorderLow, int inorderHigh) {
49+
if (preorderIndex > preorder.length-1 || inorderLow > inorderHigh) return null;
50+
51+
int currentVal = preorder[preorderIndex];
52+
TreeNode n = new TreeNode(currentVal);
53+
int mid = inorderPositions.get(currentVal);
54+
55+
n.left = builder(preorder, preorderIndex+1, inorderLow, mid-1);
56+
n.right = builder(preorder, preorderIndex + (mid - inorderLow) + 1, mid+1, inorderHigh);
57+
58+
return n;
59+
}
60+
61+
}

0 commit comments

Comments
 (0)