-
Notifications
You must be signed in to change notification settings - Fork 56
/
Solution.java
39 lines (34 loc) · 1.14 KB
/
Solution.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
27
28
29
30
31
32
33
34
35
36
37
38
39
package g1001_1100.s1008_construct_binary_search_tree_from_preorder_traversal;
// #Medium #Array #Tree #Binary_Tree #Stack #Monotonic_Stack #Binary_Search_Tree
// #Udemy_Tree_Stack_Queue #2022_02_21_Time_0_ms_(100.00%)_Space_41.8_MB_(26.01%)
import com_github_leetcode.TreeNode;
/*
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
public class Solution {
private 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;
}
}