Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
http://oj.leetcode.com/problems/convert-sorted-array-to-binary-search-tree/
Solution:
Obviously the sorted array is the result of the balanced BST. So we need to find the middle number which is the root. Then recursively build the whole tree.
https://github.com/starcroce/leetcode/blob/master/convert_sorted_array_to_binary_search_tree.cpp
// 88 ms for 32 cases
/**
* 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 *sortedArrayToBST(vector<int> &num) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
return buildTree(num, 0, num.size()-1);
}
TreeNode *buildTree(vector<int> &num, int start, int end) {
if(start > end) {
return NULL;
}
if(start == end) {
return new TreeNode(num[start]);
}
int mid = (start + end) / 2;
TreeNode *root = new TreeNode(num[mid]);
root->left = buildTree(num, start, mid-1);
root->right = buildTree(num, mid+1, end);
return root;
}
};