108.将有序数组转化为二叉搜索树
主要思路:
将数组进行分割,找到中间值,尤为关键,这时候就可以考虑使用二分搜索,但区间的开闭要确定好
class Solution {
private:
TreeNode* traversal (vector<int>& nums,int left,int right) {
if (left > right) return nullptr;
int mid = left + (right - left)/2;
TreeNode * root = new TreeNode(nums[mid]);
root->left = traversal(nums,left,mid-1);
root->right = traversal(nums,mid+1,right);
return root;
}
public:
TreeNode* sortedArrayToBST(vector<int>& nums) {
TreeNode* root = traversal (nums,0,nums.size() - 1);
return root;
}
};