109. Convert Sorted List to Binary Search Tree
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
class Solution {
public TreeNode sortedListToBST(ListNode head) {
if (head == null)
return null;
return toBST(head, null);
}
private TreeNode toBST(ListNode head, ListNode tail) {
ListNode slow = head;
ListNode fast = head;
if (head == tail)
return null;
while (fast != tail && fast.next != tail) {
fast = fast.next.next;
slow = slow.next;
}
//例如链表为1 2 3 4 5 6 7 8,则slow指向5,fast指向null,5作为thead,
TreeNode thead = new TreeNode(slow.val);
thead.left = toBST(head, slow);
thead.right = toBST(slow.next, tail);
return thead;
}
}
浙公网安备 33010602011771号