/**
* 自己的代码
* Runtime: 0 ms, faster than 100.00%
* Memory Usage: 39.6 MB, less than 88.37%
*/
class Solution {
public TreeNode sortedListToBST(ListNode head) {
int cnt = 0; // count the number of nodes in the list
ListNode p = head;
while (p != null) {
cnt++;
p = p.next;
}
return helper(head, cnt);
}
private TreeNode helper (ListNode head, int len) {
if (head == null || len <= 0) {
return null;
}
ListNode mid = head;
int leftSize = (len - 1) / 2;
for (int i = 0; i < leftSize; i++) { // find the root node
mid = mid.next;
}
TreeNode root = new TreeNode(mid.val);
root.left = helper(head, leftSize);
root.right = helper(mid.next, len - leftSize - 1);
return root;
}
}
/**
* two pointers
* Runtime: 0 ms, faster than 100.00%
* Memory Usage: 39.8 MB, less than 82.43%
*/
class Solution {
public TreeNode sortedListToBST(ListNode head) {
return helper(head, null);
}
private TreeNode helper(ListNode start, ListNode end) {
if (start == end) {
return null;
}
ListNode slow = start, fast = start;
while (fast != end && fast.next != end) { // use two pointers to find the root val
fast = fast.next.next;
slow = slow.next;
}
TreeNode root = new TreeNode(slow.val);
root.left = helper(start, slow);
root.right = helper(slow.next, end);
return root;
}
}