-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathConvertSortedListToBinarySearchTree.java
More file actions
52 lines (42 loc) · 1.2 KB
/
ConvertSortedListToBinarySearchTree.java
File metadata and controls
52 lines (42 loc) · 1.2 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
package binary_search_tree;
/**
* Description: https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree
* Difficulty: Medium
* Time complexity: O(nlog n)
* Space complexity: O(log n)
*/
public class ConvertSortedListToBinarySearchTree {
public TreeNode sortedListToBST(ListNode head) {
if (head == null) return null;
if (head.next == null) return new TreeNode(head.val);
ListNode mid = findMid(head);
TreeNode root = new TreeNode(mid.val);
root.left = sortedListToBST(head);
root.right = sortedListToBST(mid.next);
return root;
}
private ListNode findMid(ListNode head) {
ListNode slow = head;
ListNode fast = head;
ListNode prev = null;
while (fast != null && fast.next != null) {
prev = slow;
slow = slow.next;
fast = fast.next.next;
}
prev.next = null;
return slow;
}
private static class TreeNode {
int val;
TreeNode left;
TreeNode right;
public TreeNode(int val) {
this.val = val;
}
}
private static class ListNode {
int val;
ListNode next;
}
}