Thursday, November 20, 2014

Convert Sort List to Binary Search Tree LeetCode

The start position for fast and slow should be set carefully.


public TreeNode sortedListToBST(ListNode head) {
        if (head == null) return null;
        if (head.next == null) return new TreeNode(head.val);
        
        ListNode fast = head.next.next;
        ListNode slow = head;
        while (fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;
        }
        ListNode parent = slow.next;
        slow.next = null;
        TreeNode root = new TreeNode(parent.val);
        root.left = sortedListToBST(head);
        root.right = sortedListToBST(parent.next);
        
        return root;
    }

Here is a better solution. (Bottom-up)

From the CleanCodeHandbook of LeetCode.
public class Solution {
    private ListNode list;
    public TreeNode sortedListToBST(ListNode head) {
        int n = 0;
        ListNode p = head;
        while (p!=null) {
            p = p.next;
            n++;
        }
        list = head;
        return sortedListToBST(0, n-1);
    }
   
    private TreeNode sortedListToBST(int start, int end) {
        if (start > end) return null;
        int mid = (start + end)/2;
        TreeNode leftChild = sortedListToBST(start, mid-1);
        TreeNode parent = new TreeNode(list.val);
        parent.left = leftChild;
        list = list.next;
        TreeNode rightChild= sortedListToBST(mid+1, end);
        parent.right = rightChild;
        return parent;
       
    }
}

No comments:

Post a Comment