Monday, July 10, 2017

109. Convert Sorted List to Binary Search Tree[TODO]


Version #2 [TODO]
Count the size once
And take O(n) time to solve


Version #1 Two pointers
Each layer is size 2^depth

for each node, the time to find the slow pointer is O(node length)
Total length is always O(n)
So we need O(nlogn) to solve this problem

53.30 %



public class Solution {
    public TreeNode sortedListToBST(ListNode head) {
        if (head == null) return null;
        //TODO
        return sortedListToBST(head, null);
    }
    private TreeNode sortedListToBST(ListNode head, ListNode tail) {
        if (head == tail) return null;
        ListNode slow = head;
        ListNode fast = head;
        while (fast != tail && fast.next != tail) {
            slow = slow.next;
            fast = fast.next.next;
        }
        TreeNode root = new TreeNode(slow.val);
        root.left = sortedListToBST(head, slow);
        root.right = sortedListToBST(slow.next, tail);
        return root;
    }
}

No comments:

Post a Comment