1008. Construct Binary Search Tree from Preorder Traversal

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
class Solution {
public TreeNode bstFromPreorder(int[] preorder) {
// root, left, right
return bstFromPreorder(preorder, 0, preorder.length - 1);
}

private TreeNode bstFromPreorder(int[] preorder, int rootIndex, int endIndex) {
if (rootIndex > endIndex) {
return null;
}

TreeNode root = new TreeNode(preorder[rootIndex]);
if (rootIndex == endIndex) {
return root;
}

int rightStartIndex = rootIndex + 1;
while (rightStartIndex < preorder.length && preorder[rightStartIndex] < preorder[rootIndex]) {
rightStartIndex++;
}
root.left = bstFromPreorder(preorder, rootIndex + 1, rightStartIndex - 1);
root.right = bstFromPreorder(preorder, rightStartIndex, endIndex);
return root;
}
}

References

1008. Construct Binary Search Tree from Preorder Traversal