Wednesday, July 16, 2014

Convert Sorted Array to Binary Search Tree

Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

对排好序的数组二分,中点就是root,左边部分左子树,右边部分右子树
public class Solution {
    //Time: O(n)  
    public TreeNode sortedArrayToBST(int[] num) {
        if (num == null || num.length == 0) {
            return null;
        }
        return convert(num, 0, num.length - 1);
    }
    
    private TreeNode convert(int[] num, int start, int end) {
        if (start > end) {
            return null;
        }
        
        int mid = start + (end - start) / 2;
        TreeNode root = new TreeNode(num[mid]);
        root.left = convert(num, start, mid - 1);
        root.right = convert(num, mid + 1, end);
        return root;
    }
}

No comments:

Post a Comment