2014年4月23日 星期三

[LeetCode] Convert Sorted Array to Binary Search Tree

Problem:
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
Solution:O(n)
public class Solution {
    public TreeNode sortedArrayToBST(int[] num) {
        return doBST(num,0,num.length-1);
    }
    public TreeNode doBST(int[] num, int start, int end){
        if(start > end)
            return null;
        int middle = (start+end) / 2;
        TreeNode root = new TreeNode(num[middle]);
        root.left= doBST(num, start, middle-1);
        root.right= doBST(num, middle+1, end);
        return root;
    }
}

沒有留言:

張貼留言