Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
My code:
public TreeNode sortedListToBST(ListNode head) {
if(head==null) return null;
ListNode slow = head, fast = head;
ListNode pre = null;
while(fast!=null&&fast.next!=null){
pre = slow;
slow = slow.next;
fast=fast.next.next;
}
if(pre != null)
pre.next = null;
else
head = null;
TreeNode root = new TreeNode(slow.val);
root.left = sortedListToBST(head);
root.right = sortedListToBST(slow.next);
return root;
}
总结:基本思路是对的,但是看了参考答案。要考虑pre==null的情形。另外如果fast==null了,根本不存在fast.next了。