Skip to main content

Convert Sorted Array to Binary Search Tree


Convert Sorted Array to Binary Search Tree: Given an integer array nums where the elements are sorted in ascending order, convert it to a height-balanced binary search tree. A height-balanced binary tree is a binary tree in which the depth of the two subtrees of every node never differs by more than one.

Example 1:

image

Input: nums = [-10,-3,0,5,9]
Output: [0,-3,9,-10,null,5]
Explanation: [0,-10,5,null,-3,null,9] is also accepted.

Example 2:

image

Input: nums = [1,3]
Output: [3,1]
Explanation: [1,null,3] and [3,1] are both height-balanced BSTs.

Constraints:
  • 1 <= nums.length <= 10^4
  • -10^4 <= nums[i] <= 10^4
  • nums is sorted in a strictly increasing order.

Try this Problem on your own or check similar problems:

  1. Convert Sorted List to Binary Search Tree
Solution:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
return helper(nums, 0, nums.length - 1);
}

private TreeNode helper(int[] nums, int start, int end){
if(start > end) return null;
int mid = start + (end - start) / 2;
TreeNode root = new TreeNode(nums[mid]);
root.left = helper(nums, start, mid - 1);
root.right = helper(nums, mid + 1, end);
return root;
}
}

Time/Space Complexity:
  • Time Complexity: O(n)
  • Space Complexity: O(logn)

Explanation:

The algorithm for getting balanced binary search tree (BST) is simple when we have a sorted array as input since we can just pick the middle index array element as value for the root and recursively build the left and right subtree using the left and right side of middle element in the input array respectively. Note that we calculate middle element start + (end - start) / 2 it produces the same result as (start + end) / 2 but it copes with overflow if the boundaries are large integers. Total time complexity is proportional to the input array elements, while since we have height balanced tree total space complexity spend on recursion stack will be the height of the tree O(logn). We return the new formed root as our final solution.