题目:
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
思路:类似二分法,中间向左右两边找child.
class Solution {
public:
TreeNode* buildBST_helper(const vector<int>& num, int lower_bound, int upper_bound) {
if (lower_bound > upper_bound) return nullptr;
int mid = (lower_bound + upper_bound) / 2;
TreeNode* new_root = new TreeNode(num[mid]);
new_root->left = buildBST_helper(num, lower_bound, mid - 1);
new_root->right = buildBST_helper(num, mid + 1, upper_bound);
return new_root;
}
TreeNode *sortedArrayToBST(vector<int> &num) {
return buildBST_helper(num, 0, num.size() - 1);
}
};
总结:复杂度为O(n).