lintcode-medium-Convert Sorted List to Balanced BST

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

               2
1->2->3  =>   / \
             1   3


/**
 * Definition for ListNode.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int val) {
 *         this.val = val;
 *         this.next = null;
 *     }
 * }
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */ 
public class Solution {
    /**
     * @param head: The first node of linked list.
     * @return: a tree node
     */
    public TreeNode sortedListToBST(ListNode head) {  
        // write your code here
        
        if(head == null)
            return null;
        if(head.next == null)
            return new TreeNode(head.val);
        
        ListNode slow = head;
        ListNode fast = head;
        
        while(fast != null && fast.next != null){
            slow = slow.next;
            fast = fast.next.next;
        }
        
        ListNode head2 = slow.next;
        
        ListNode p = head;
        while(p.next != slow)
            p = p.next;
        
        p.next = null;
        
        TreeNode root = new TreeNode(slow.val);
        TreeNode left = sortedListToBST(head);
        TreeNode right = sortedListToBST(head2);
        
        root.left = left;
        root.right = right;
        
        return root;
    }
}

 

posted @ 2016-03-16 13:14  哥布林工程师  阅读(136)  评论(0编辑  收藏  举报