样例
2
1->2->3 => / \
1 3
public TreeNode sortedListToBST(ListNode head) {
// write your code here
if (head == null) {
return null;
}
return helper(head,null);
}
public TreeNode helper(ListNode head,ListNode end) {
if (head == end) {
return null;
}
ListNode fast = head.next;
ListNode slow = head;
while (fast != end && fast.next != end) {
fast = fast.next.next;
slow = slow.next;
}
TreeNode root = new TreeNode(slow.val);
root.left = helper(head,slow);
root.right = helper(slow.next,end);
return root;
}