码迷,mamicode.com
首页 > 其他好文 > 详细

Convert Sorted List to Binary Search Tree

时间:2015-04-08 14:54:59      阅读:125      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!