Convert Sorted Array to Binary Search Tree

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

public class Solution {
    public TreeNode sortedArrayToBST(int[] nums) {
        if (nums.length == 0) 
            return null; 
            
        return sortedArrayToBSTHelper (nums, 0, nums.length - 1);
    }
    
    public TreeNode sortedArrayToBSTHelper (int[] nums, int start, int end) {
        if (start > end) 
            return null; 
       
        int mid = (start + end) / 2;
		TreeNode root = new TreeNode(nums[mid]);
		root.left = sortedArrayToBSTHelper(nums, start, mid - 1);
		root.right = sortedArrayToBSTHelper(nums, mid + 1, end);
		return root; 
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s