Tuesday, July 14, 2015

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.
Have you met this question in a real interview? 
Yes

Example
               2
1->2->3  =>   / \
             1   3
public class Solution {
    /**
     * @param head: The first node of linked list.
     * @return: a tree node
     */
    static ListNode head;
    public TreeNode sortedListToBST(ListNode head) {  
        // write your code here
        ListNode run = head;
        this.head = head;
        int len = 0;
        while(run != null){
            len++;
            run = run.next;
        }
       return _building(0, len - 1);
    }
    
    private TreeNode _building(int start, int end){
        if(start > end){
            return null;
        }
        int mid = (start + end) / 2; 
        TreeNode left = _building(start, mid - 1);
        TreeNode root = new TreeNode(head.val);
        head = head.next;
        root.left = left;
        root.right = _building(mid + 1, end);
        return root;
    }
}

No comments:

Post a Comment