How to convert a sorted array to a binary search tree
Given sorted array in ascending order, return a height-balanced binary search tree
A height-balanced binary tree is a
binary treein which the depth of the two subtrees of every node never differs by more than1
Example 1
Input: [1, 2, 3]
Output: 2
/ \
1 3
Example 2
Input: [0, 1, 2, 3]
Output: 1
/ \
0 2
\
3
A tree node is represented like this:
public class TreeNode
{
public int Value;
public TreeNode Left;
public TreeNode Right;
public TreeNode(int value)
{
Value = value;
}
}
Algorithm
A binary Search Tree (BST) is a binary tree where each node has a key and meet the following requirements:
- The
left subtreeof a node contains nodes with keyssmallerthan the node's key - The
right subtreeof a node contains nodes with keyslargerthan the node's key - The
leftandrightsubtree arebinary search trees
We can use the knowledge that the array is sorted. We can divide the array into two equal parts and assign the mid-value as a root node. The elements in the array to the left of the mid-value would the left subtree and the elements in the array to the right of the mid-value would the right subtree.
- get the
middleof thearrayand make it asroot - recursively do the same for the
left halfand theright half- get the
middleof theleft halfand make it theleft childof theroot - get the
middleof theright halfand make it theright childof theroot
- get the

Code
public TreeNode Convert(int[] array)
{
if (array == null || array.Length == 0)
{
return null;
}
return Convert(array, 0, array.Length - 1);
}
private static TreeNode Convert(int[] array, int lo, int hi)
{
if (lo > hi)
{
return null;
}
int mid = lo + (hi - lo) / 2;
var root = new TreeNode(array[mid]);
root.Left = Convert(array, lo, mid - 1);
root.Right = Convert(array, mid + 1, hi);
return root;
}
Time Complexity: O(n)
Recent articles
Nice to read