Leetcode–Convert Sorted List to Binary Search Tree

The Problem:

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

Notes:

  1. Similar to Convert Sorted Array to Binary Search Tree, but in this problem we don’t have easy access to the middle element.
  2. A bottom-up approach is used here, the treenodes will be constructed by the order of listnode in p. The trick is keep a pointer to the current ListNode p, p is “global” and gets updated in each recursion. So inside each recursion, treenode should be constructed exactly in order left->parent->right, because p will get updated in branches also.

Java Solution

/**
 * 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 ListNode p; // p need to be passed in and out of constructTree
    public TreeNode sortedListToBST(ListNode head) {
        int len = getLength(head);
        if(len == 0) return null;
        p = head;
        return constructTree(0, len-1);
    }
    
    private int getLength(ListNode head){
        int len = 0;
        while(head!= null){
            head = head.next;
            len++;
        }
        return len;
    }
    
    private TreeNode constructTree(int start, int end){
        if(start > end) return null;
        int mid = (start+end)/2;
        TreeNode parent = new TreeNode(0);
        //--!!--here the order should be :
        // 1. left (p got updated there also) 2. parent (AND UPDATE p) 3. right
        parent.left = constructTree(start, mid-1);
        parent.val = p.val;
        p = p.next;
        parent.right = constructTree(mid+1, end);
        return parent;
    }
}

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