public class Solution {
public TreeNode sortedListToBST(ListNode head) {
if(head == null) return null;
if(head.next == null) return new
TreeNode(head.val);
ArrayList<Integer> list=new
ArrayList<Integer>();
while(head!=null)
{
list.add(head.val);
head=head.next;
}
return buildToBST(list,0,list.size()-1);
}
private TreeNode buildToBST(ArrayList<Integer>
list, int start, int end) {
if(end<start)return null;
int mid=(start+end+1)/2;//题目中是要求偶数时候,中间2个,选后面那个数
TreeNode root = new TreeNode(list.get(mid));
root.left=buildToBST(list,start,mid-1);
root.right=buildToBST(list,mid+1,end);
return root;
}
// public TreeNode sortedListToBST(ListNode head)
{//这个也是对的,没有上面的那个快
// if(head == null) return null;
// if(head.next == null) return new
TreeNode(head.val);
// ListNode mid = head;
// ListNode end = head;
// ListNode preMid = null;
// while (end != null && end.next != null)
{//每一次都循环快慢指针找中点
// preMid = mid;
// mid = mid.next;
// end = end.next.next;
// }
// TreeNode root = new TreeNode(mid.val);
// preMid.next = null;
// root.left = sortedListToBST(head);
// root.right = sortedListToBST(mid.next);
// return root;
// }
}