首页 > 其他 > 详细

Convert Sorted List to Binary Search Tree

时间:2015-04-08 14:52:26      阅读:166      评论:0      收藏:0      [点我收藏+]
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;
    }
}

二分法查找

Convert Sorted List to Binary Search Tree

原文:http://www.cnblogs.com/jiajiaxingxing/p/4402121.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!