一:题目
二:上码
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* sortedArrayToBST(vector<int>& nums,int left,int right) {
if(left > right) return NULL;//这里是我们在处理数组的边界是左闭右闭
int mid = (left+right)/2;
TreeNode* node = new TreeNode(nums[mid]);
node->left = sortedArrayToBST(nums,left,mid-1);
node->right = sortedArrayToBST(nums,mid+1,right);
return node;
}
TreeNode* sortedArrayToBST(vector<int>& nums) {
TreeNode* root = sortedArrayToBST(nums,0,nums.size()-1);
return root;
}
};