问题:
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
分析:
简单的一道递归题。
代码:
class Solution {
public:
TreeNode *sortedArrayToBST(const vector<int> &num, int start, int end) {
if (start > end) return 0;
if (start == end) return new TreeNode(num[start]);
int mid = (start + end) / 2;
TreeNode *root = new TreeNode(num[mid]);
root->left = sortedArrayToBST(num, start, mid - 1);
root->right = sortedArrayToBST(num, mid + 1, end);
return root;
}
TreeNode *sortedArrayToBST(vector<int> &num) {
int len = num.size();
if (len == 0) return 0;
if (len == 1) return (new TreeNode(num[0]));
return sortedArrayToBST(num, 0, len - 1);
}
};