I am currently checking about coding an algorithms. If we have the following case:
Given a sorted (increasing order) array with unique integer elements, wrote an alg
middle of the array and make it as rootmiddle of the left half and make it the left child of the rootmiddle of the right half and make it the right child of the root 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)
from CodeStandard