Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
和数组相比,不能通过下标快速找到中位数做根节点,用快慢指针法寻找根节点。
public class Solution {
public TreeNode sortedListToBST(ListNode head) {
if (head == null) return null;
return sortedListToBST(head, null);
}
public TreeNode sortedListToBST(ListNode head, ListNode tail) {
if (head == tail) return null;
ListNode slow = head,fast = head; //快慢指针法找根节点
while(fast != tail && fast.next != tail){
fast = fast.next.next;
slow = slow.next;
}
TreeNode root = new TreeNode(slow.val);
root.left = sortedListToBST(head, slow);
root.right = sortedListToBST(slow.next, tail);
return root;
}
}