BiruLyu
5/25/2017 - 6:20 PM

109. Convert Sorted List to Binary Search Tree.java

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public TreeNode sortedListToBST(ListNode head) {
        if(head == null) return null;
        return helper(head,null);
    }
    
    public TreeNode helper(ListNode head, ListNode tail){
        ListNode fast = head;
        ListNode slow = head;
        if(head == tail) return null;
        
        //while(fast != tail && fast.next != tail){
        //[1,2,3,4,5][1,2,3,4]
        //[3,2,5,1,null,4][3,2,4,1]
        while(fast.next != tail && fast.next.next != tail){
        //[1,2,3,4,5][1,2,3,4]
        //[3,1,4,null,2,null,5][2,1,3,null,null,null,4]
            fast = fast.next.next;
            slow = slow.next;
        }
        
        TreeNode root = new TreeNode(slow.val);
        root.left = helper(head, slow);
        root.right = helper(slow.next, tail);
        return root;
    }
}