Convert Sorted Array to Balanced Binary Search Tree (BST)

时间:2022-12-18 15:43:28

(http://leetcode.com/2010/11/convert-sorted-array-into-balanced.html)

Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

Code:

BinaryTree* sortedArrayToBST(int arr[], int start, int end)
{
if (start > end)
return NULL;
int mid = start + (end - start) / ;
BinaryTree* node = new BinaryTree(arr[mid]);
node->left = sortedArrayToBST(arr, start, mid-);
node->right = sortedArrayToBST(arr, mid+, end);
return node;
} BinaryTree* sortedArrayToBST(int arr[], int n)
{
return sortedArrayToBST(arr, , n-);
}