Convert Sorted List to Binary Search Tree

Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.

Solution

/**
 * 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;
        }

        ListNode runner = head;
        while (runner.next != null) {
            runner = runner.next;
        }

        return  sortedListToBST(head, runner);

    }

    public TreeNode sortedListToBST(ListNode start, ListNode end) {
        if (start == null || end == null) {
            return null;
        }

        ListNode runnerCheck = start;
        while (!runnerCheck.equals(end) ) {
            runnerCheck = runnerCheck.next;
        }

        if (!runnerCheck.equals(end)) {
            return null;
        }

        if (start.equals(end)) {
            return new TreeNode(start.val);
        }

        if (start.next.equals(end)) {
            TreeNode one = new TreeNode(start.val);
            TreeNode two = new TreeNode(end.val);
            two.left = one;
            return two;
        }

        ListNode prev = null;
        ListNode slow = start;
        ListNode fast = start;

        while (fast != end && fast.next != end) {
            prev = slow;
            slow = slow.next;
            fast = fast.next.next;
        }

        TreeNode root = new TreeNode(slow.val);
        root.left = sortedListToBST(start, prev);
        root.right = sortedListToBST(slow.next, end);

        return root;
    }
}

results matching ""

    No results matching ""