public class Solution {
public TreeNode sortedListToBST(ListNode head) {
if (head == null)
return null;
if (head.next == null)
return new TreeNode (head.val);
ListNode slow = head;
ListNode fast = head;
ListNode pre = null;
ListNode mid = null;
while (fast.next != null && fast != null){
pre = slow;
fast = fast.next.next;
slow = slow.next;
}
mid = slow;
pre.next = null;
TreeNode root = new TreeNode(slow.val);
root.right = sortedListToBST(mid.next);
root.left = sortedListToBST(head);
return root;
}
}
This is my solution but it shows: java.lang.NullPointerException
when i change
while (fast.next != null && fast != null){
to
while (fast != null && fast.next != null){
the solution is accepted
i don't know the differences between them.