-
Notifications
You must be signed in to change notification settings - Fork 277
/
ConvertSortedListToBST.java
61 lines (43 loc) · 1.31 KB
/
ConvertSortedListToBST.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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
// Solution for 108 Convert Sorted Array to BST
class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
if(nums.length == 0){
return null;
}
return helper(nums, 0, nums.length-1);
}
private TreeNode helper(int[] nums, int startIndex, int endIndex){
if(startIndex> endIndex){
return null;
}
int midIndex = (startIndex + endIndex)/2;
TreeNode newNode = new TreeNode(nums[midIndex]);
newNode.left = helper(nums, startIndex, midIndex-1);
newNode.right = helper(nums, midIndex+1, endIndex);
return newNode;
}
}
// Solution for 109 Convert sorted list to BST
class Solution {
public TreeNode sortedListToBST(ListNode head) {
if(head==null){
return null;
}
return helper(head, null);
}
private TreeNode helper(ListNode start, ListNode end){
ListNode fast =start;
ListNode slow = start;
if(start == end) {
return null;
}
while(fast!=end && fast.next!=end){
fast = fast.next.next;
slow = slow.next;
}
TreeNode newNode = new TreeNode(slow.val);
newNode.left = helper(start, slow);
newNode.right = helper(slow.next, end);
return newNode;
}
}