Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
void foo(int A[], int left, int right, TreeNode **ppNode)
{
if (left > right)
return;
if (left == right)
{
TreeNode *curNode = new TreeNode(A[left]);
(*ppNode) = curNode;
}
else
{
int mid = (left+right)/2;
TreeNode *curNode = new TreeNode(A[mid]);
foo(A, left, mid-1, &curNode->left);
foo(A, mid+1, right, &curNode->right);
(*ppNode) = curNode;
}
}
public:
TreeNode *sortedArrayToBST(vector<int> &num) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (num.size() == 0)
return NULL;
int left = 0;
int right = num.size()-1;
int mid = (left+right)/2;
TreeNode *pRoot = new TreeNode(num[mid]);
foo(&num[0], left, mid-1, &(pRoot->left));
foo(&num[0], mid+1, right, &(pRoot->right));
return pRoot;
}
};