-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathConvertSortedListToBinarySearchTree.java
More file actions
36 lines (30 loc) · 1.03 KB
/
ConvertSortedListToBinarySearchTree.java
File metadata and controls
36 lines (30 loc) · 1.03 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
// https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree
// T: O(n)
// S: O(n)
import java.util.ArrayList;
import java.util.List;
public class ConvertSortedListToBinarySearchTree {
public TreeNode sortedListToBST(ListNode head) {
final List<Integer> list = toList(head);
return listToBST(list);
}
private TreeNode listToBST(List<Integer> list) {
return listToBST(list, 0, list.size());
}
private TreeNode listToBST(List<Integer> list, int start, int end) {
if (start == end) return null;
final int middle = start + (end - start) / 2;
final TreeNode root = new TreeNode(list.get(middle));
root.left = listToBST(list, start, middle);
root.right = listToBST(list, middle + 1, end);
return root;
}
private List<Integer> toList(ListNode head) {
final List<Integer> result = new ArrayList<>();
while (head != null) {
result.add(head.val);
head = head.next;
}
return result;
}
}