Convert Sorted Array to Binary Search Tree
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 {
public:
TreeNode *buildTree(vector<int> &num, int begin, int end)
{
if(begin >= end)
{
return NULL;
}
int mid = (begin + end - 1)/2;
TreeNode* p = new TreeNode(num[mid]);
TreeNode* lc = buildTree(num, begin, mid);
TreeNode* lr = buildTree(num, mid+1, end);
p->right = lr;
p->left = lc;
return p;
}
TreeNode *sortedArrayToBST(vector<int> &num) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
return buildTree(num, 0, num.size());
}
};