109. Convert Sorted List to Binary Search Tree
https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/discuss/35476/Share-my-JAVA-solution-1ms-very-short-and-concise.
1 class Solution { 2 public TreeNode sortedListToBST(ListNode head) { 3 return helper(head, null); 4 5 } 6 7 public TreeNode helper(ListNode head, ListNode last) { 8 if(head == last) { 9 return null; 10 } 11 ListNode slow = head; 12 ListNode fast = head; 13 while(fast.next != last && fast.next.next != last) { // 这里是不等于last 14 fast = fast.next.next; 15 slow = slow.next; 16 } 17 TreeNode root = new TreeNode(slow.val); 18 root.left = helper(head, slow); 19 root.right = helper(slow.next, last); 20 return root; 21 } 22 23 }