2014年2月13日星期四

LeetCode - 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) {
        if(head==null) {
            return null;
        }
        return build(head, null);
    }
   
    private TreeNode build(ListNode from, ListNode end) {
        if(from==null || from==end) {
            return null;
        }
        if(from.next==end) {
            return new TreeNode(from.val);
        }
        ListNode p1 = from;
        ListNode p2 = from;
        while(p2.next!=end && p2.next.next!=end) {
            p1 = p1.next;
            p2 = p2.next.next;
        }
        TreeNode root = new TreeNode(p1.val);
        root.left = build(from, p1);
        root.right = build(p1.next, end);
        return root;
    }
}

没有评论:

发表评论