108. Convert Sorted Array to Binary Search Tree

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

 

Subscribe to see which companies asked this question

Hide Tags
 Tree Depth-first Search
 

 

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public TreeNode sortedArrayToBST(int[] nums) {
        return createTree(nums, 0, nums.length);
    }
    
    private TreeNode createTree(int[] nums, int from, int to)
    {
        if(from>=to)
            return null;
        int len = to - from;
        if(len==1)
            return new TreeNode(nums[from]);
        
        int rootIndexOffset = len%2==0 ? len/2 : (len-1)/2;
        int rootIndex = from + rootIndexOffset;
        TreeNode root = new TreeNode(nums[rootIndex]);
        root.left = createTree(nums, from, rootIndex);
        root.right = createTree(nums, rootIndex+1, to);

        return root;
    }
}

 

posted @ 2016-03-14 08:16  新一代的天皇巨星  阅读(132)  评论(0)    收藏  举报