Convert Sorted Array to Binary Search Tree && Convert Sorted List to Binary Sear

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public TreeNode sortedArrayToBST(int[] num) {
        // Start typing your Java solution below
        // DO NOT write main() function
        int length = num.length;
        if (length == 0)
            return null;
        int[] left = Arrays.copyOfRange(num, 0, length/2);
        int[] right = (length/2+1 < length) ? Arrays.copyOfRange(num, length/2+1, length) : new int[0];
        TreeNode tree = new TreeNode(num[length/2]);
        tree.left = sortedArrayToBST(left);
        tree.right = sortedArrayToBST(right);
        return tree;
    }
}

算法很简单,递归的方法,类似快排,因为数组随机访问很快,所以第一题很简单。但是linkedlist就比较麻烦了。我想了一个比较山寨的方法,先遍历一遍,把所有的ListNode都放到一个数组里,然后再用第一题对数组的代码= =不知道大家又什么其他好的方法
/**
 * 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) {
        // Start typing your Java solution below
        // DO NOT write main() function
        ListNode current = head;
        ArrayList<Integer> array = new ArrayList<Integer>();
        while (current != null){
            array.add(current.val);
            if (current.next != null)
                current = current.next;
            else
                break;
        }
        int[] list = new int[array.size()];
        for (int i = 0; i < array.size(); ++i)
            list[i] = array.get(i).intValue();
        return sortedArrayToBST(list);
    }
    
    public TreeNode sortedArrayToBST(int[] num) {
        // Start typing your Java solution below
        // DO NOT write main() function
        int length = num.length;
        if (length == 0)
            return null;
        int[] left = Arrays.copyOfRange(num, 0, length/2);
        int[] right = (length/2+1 < length) ? Arrays.copyOfRange(num, length/2+1, length) : new int[0];
        TreeNode tree = new TreeNode(num[length/2]);
        tree.left = sortedArrayToBST(left);
        tree.right = sortedArrayToBST(right);
        return tree;
    }
    
}

第二题还需要注意的就是第一次遍历的时候虽然不能继续往后找了,但是还是需要把val加到数组里,这里和之前的操作不太一样。还有就是ArrayList<Intger>转换int[]的方法,我没找到很优雅的方法,所以只能手写循环了,sigh

你可能感兴趣的:(Binary search)