Convert Sorted Array to Binary Search Tree

Monisha Mathew
1 min readMay 28, 2019

--

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

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

You may view the full question here.

Approach 1: There isn’t a unique solution for this question. Here’s one approach that uses recursion —

//Approach 1:
//Runtime: 0ms
//Memory usage: 35.2MB
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
return sort(nums, 0, nums.length-1);
}

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

Find more posts here.

Cheers & Chao!

--

--