Problem: Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
Approach: Binary search is obvious choice here.
public BinarySearchTree(int[] sortedArray)
{
if (sortedArray != null)
{
this.Root = this.SortedArrayToBST(sortedArray, 0, sortedArray.Count() - 1);
}
}
public BinaryTreeNode SortedArrayToBST(int[] sortedArray, int start, int end)
{
if (start > end)
{
return null;
}
int mid = (start + end) / 2;
BinaryTreeNode node = new BinaryTreeNode(sortedArray[mid]);
node.LeftNode = this.SortedArrayToBST(sortedArray, start, mid - 1);
node.RightNode = this.SortedArrayToBST(sortedArray, mid + 1, end);
return node;
}
No comments:
Post a Comment