Middle-题目56:109. Convert Sorted List to Binary Search Tree

题目原文:
iven a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
题目大意:
把单链表转换成二叉平衡树。
题目分析:
把单链表转换成数组,再调用Middle-题目15的函数就可以了。如果要直接做的话,使用快慢指针法找到中点,再递归即可。
源码:(language:java)

public class Solution {
    public TreeNode sortedListToBST(ListNode head) {
        List<Integer> list = new ArrayList<Integer>();
        for(ListNode temp = head;temp!=null;temp=temp.next)
            list.add(temp.val);
        Integer[] nums = new Integer[list.size()];
        return sortedArrayToBST(list.toArray(nums));
    }
    public TreeNode sortedArrayToBST(Integer[] nums) {
        if(nums.length==0)
            return null;
        TreeNode bst=createBST(nums,0,nums.length-1);
        return bst;
    }
    public TreeNode createBST(Integer[] nums,int start,int end) {
        int mid = (start + end) / 2;
        TreeNode root = new TreeNode(nums[mid]);
        if(start < mid ) 
            root.left = createBST(nums,start,mid-1);
        if(mid  < end) 
            root.right = createBST(nums,mid+1,end); 
        return root;
    }
}

成绩:
4ms,beats 1.06%,众数1ms, 59.87%

你可能感兴趣的:(Middle-题目56:109. Convert Sorted List to Binary Search Tree)