Saturday, January 10, 2015

LeetCode 109: 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.
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; next = null; }
 * }
 */
/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public TreeNode sortedListToBST(ListNode head) {
        // Half divide to get the root node and obtain two parts;
        // Half divide left part to get root.left;
        // half divide right part to get root.right.
        Map<Integer, ListNode> map = new HashMap<>();
        int count = 0; // Number of nodes
        
        for (ListNode node = head; node != null; node = node.next)
            map.put(count++, node);
            
        int lo = 0, hi = count-1;
        
        return genTree(map, lo, hi);
    }
    
    private TreeNode genTree(Map<Integer, ListNode> map, int lo, int hi)
    {
        if (lo > hi)
            return null;
            
        int mid = lo + (hi-lo)/2;
            
        TreeNode root = new TreeNode(map.get(mid).val);
        
        root.left = genTree(map, lo, mid-1);
        root.right = genTree(map, mid+1, hi);
        
        return root;
    }
}

No comments:

Post a Comment