-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1008ConstructBinarySearchTreefromPreorderTraversal.java
More file actions
80 lines (67 loc) · 2.29 KB
/
1008ConstructBinarySearchTreefromPreorderTraversal.java
File metadata and controls
80 lines (67 loc) · 2.29 KB
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
//https://leetcode.com/problems/construct-binary-search-tree-from-preorder-traversal/
/**
* 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;
* }
* }
*/
class Solution {
TreeNode bstFromPreorderStackSolution(int[] preorder) {
Stack<TreeNode> stack = new Stack();
TreeNode root = new TreeNode(preorder[0]);
stack.push(root);
for(int i = 1; i < preorder.length; i++) {
TreeNode currentNode = new TreeNode(preorder[i]);
if(preorder[i] < stack.peek().val) {
stack.peek().left = currentNode;
}
else {
TreeNode recentlyPopped = null;
while(!stack.isEmpty() && stack.peek().val < preorder[i]) {
recentlyPopped = stack.pop();
}
recentlyPopped.right = currentNode;
}
stack.push(currentNode);
}
return root;
}
public TreeNode bstFromPreorder(int[] preorder) {
//return bstFromPreorder(preorder, 0, preorder.length - 1);
return bstFromPreorderStackSolution(preorder);
}
TreeNode bstFromPreorder(int[] preorder, int start, int end) {
if(start > end) {
return null;
}
TreeNode root = new TreeNode(preorder[start]);
int rightIndex = binarySearch(preorder, start + 1, end, preorder[start]);
root.left = bstFromPreorder(preorder, start + 1, rightIndex - 1);
root.right = bstFromPreorder(preorder, rightIndex, end);
return root;
}
int binarySearch(int[] arr, int start, int end, int key) {
while(start <= end) {
int mid = start + (end - start) / 2;
if(arr[mid] == key) {
return mid;
}
if(arr[mid] < key) {
start = mid + 1;
}
else {
end = mid - 1;
}
}
return start;
}
}