Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
class Solution {
public:
TreeNode* build(vector<int>& nums, int left, int right) {
if (left > right){
return NULL;
}
float pRootIndex = round(((float)right + (float)left) / 2);
TreeNode * root = new TreeNode(nums[pRootIndex]);
root->left = build(nums, left, pRootIndex - 1);
root->right = build(nums, pRootIndex + 1, right);
return root;
}
TreeNode* sortedArrayToBST(vector<int>& nums) {
TreeNode * root = NULL;
root = build(nums,0,nums.size()-1);
return root;
}
};
思路心得
没什么的,就是简单的二分查找和递归。注意边界即可