forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_1008.java
26 lines (22 loc) · 865 Bytes
/
_1008.java
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
package com.fishercoder.solutions;
import com.fishercoder.common.classes.TreeNode;
public class _1008 {
public static class Solution1 {
/**
* credit: https://leetcode.com/problems/construct-binary-search-tree-from-preorder-traversal/discuss/252232/JavaC%2B%2BPython-O(N)-Solution
*/
int i = 0;
public TreeNode bstFromPreorder(int[] preorder) {
return bstFromPreorder(preorder, Integer.MAX_VALUE);
}
private TreeNode bstFromPreorder(int[] preorder, int bound) {
if (i == preorder.length || preorder[i] > bound) {
return null;
}
TreeNode root = new TreeNode(preorder[i++]);
root.left = bstFromPreorder(preorder, root.val);
root.right = bstFromPreorder(preorder, bound);
return root;
}
}
}