Permalink
Switch branches/tags
Nothing to show
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
30 lines (25 sloc) 742 Bytes
problem:
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
-------------------------------------------------------------------
solution:
////////////////////////
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
TreeNode *sortedArrayToBST_aux(vector<int> &num, int begin, int end)
{
if(begin > end)
return NULL;
int mid = (begin + end) / 2;
TreeNode *root = new TreeNode(num[mid]);
root->left = sortedArrayToBST_aux(num, begin, mid - 1);
root->right = sortedArrayToBST_aux(num, mid + 1, end);
return root;
}
TreeNode *sortedArrayToBST(vector<int> &num)
{
return sortedArrayToBST_aux(num, 0, num.size() - 1);
}