🌟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.


public class Solution {
    private ListNode current; 
    public TreeNode sortedListToBST(ListNode head) {
        int size = getListLength(head); 
        current = head; 
        return sortedListToBSTHelper(size); 
    }
    
    public TreeNode sortedListToBSTHelper (int size) {
        if (size <= 0 ) {
            return null; 
        }
        TreeNode left = sortedListToBSTHelper(size/2);
        TreeNode root = new TreeNode (current.val);
        current = current.next; 
        TreeNode right = sortedListToBSTHelper (size - 1 - size/2);
        
        root.left = left; 
        root.right = right;
        
        return root; 
    }
    
    
    private int getListLength (ListNode head) {
        int size = 0; 
        while (head != null) {
            size++; 
            head = head.next; 
        }
        return size; 
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s