# Blogs Hub

### by Sumit Chourasia | Oct 06, 2020 | Category :coding | Tags : algorithmbinary-treedata-structureeasyleetcodetree #### Convert Sorted Array to Binary Search Tree - Tree - Easy - LeetCode

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.

Example:

Given the sorted array: [-10,-3,0,5,9],

One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:

0
/ \
-3   9
/   /
-10  5

``````/**
* Definition for a binary tree node.
* public class TreeNode {
*     public int val;
*     public TreeNode left;
*     public TreeNode right;
*     public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
*         this.val = val;
*         this.left = left;
*         this.right = right;
*     }
* }
*/
public class Solution {
public TreeNode SortedArrayToBST(int[] nums) {
var tree = Helper(nums,0,nums.Length-1);
return tree;
}

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

Time Complexity: O(n)

Space Complexity: O(1)