-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathP_109.java
More file actions
27 lines (24 loc) · 821 Bytes
/
Copy pathP_109.java
File metadata and controls
27 lines (24 loc) · 821 Bytes
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
package leetcode.medium;
import utils.DataStructures.ListNode;
import utils.DataStructures.TreeNode;
@SuppressWarnings({ "ConstantConditions", "ReturnOfNull" })
public class P_109 {
public TreeNode sortedListToBST(ListNode head) {
if (head == null) {
return null;
}
final ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode slow = dummy;
ListNode fast = dummy;
while (fast.next != null && fast.next.next != null) {
fast = fast.next.next;
slow = slow.next;
}
final ListNode right = slow.next.next;
final ListNode root = slow.next;
slow.next.next = null;
slow.next = null;
return new TreeNode(root.val, sortedListToBST(dummy.next), sortedListToBST(right));
}
}