Convert Sorted List to Binary Search Tree

public class Solution {
    public TreeNode sortedListToBST(ListNode head) {
        if(head==null) return null;
        int len = 0;
        ListNode t = head;
        while(t!=null){
            len++;
            t = t.next;
        }
        if(len==1) return new TreeNode(head.val);
        return findRoot(0, len-1, head);
    }
    public TreeNode findRoot(int start, int end, ListNode n){
        if(start>end) return null;
        ListNode t = n;
        int mid = start +(end-start)/2;
        for(int i=start; i<mid; i++){
            t = t.next;
        }
        TreeNode root = new TreeNode(t.val);
        root.left = findRoot(start,mid-1, n);
        root.right = findRoot(mid+1,end,t.next);
        return root;
    }
}

二分法查找

posted @ 2015-04-08 13:00  世界到处都是小星星  阅读(107)  评论(0编辑  收藏  举报