Quesiton
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
My C# Solution
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode SortedArrayToBST(int[] nums) {
if (nums == null) return null;
return GetTreeNode(nums, 0, nums.Length - 1);
}
private TreeNode GetTreeNode(int[] nums, int low, int high)
{
TreeNode result = null;
if (low <= high)
{
var mid = (low + high) / 2;
result = new TreeNode(nums[mid]);
result.left = GetTreeNode(nums, low, mid - 1);
result.right = GetTreeNode(nums, mid + 1, high);
}
return result;
}
}