思路,把数组分割为2部分,左右长度相差不超过1,每次都是递归的二等分原有数组,这样就可以保证分割insert之后的数是BST而且是平衡的了!也算是一个结论吧!
class Solution {
public:
TreeNode* sortedArrayToBST(vector<int>& nums) {
TreeNode* root=NULL;
int sz=nums.size();
insert(nums,root,0,sz-1);
return root;
}
void insert(vector<int>& v,TreeNode*& root, int l,int r){
if(l<=r){
int mid=(l+r)/2;
if(!root)
root=new TreeNode(v[mid]);
insert(v,root->left,l,mid-1);
insert(v,root->right,mid+1,r);
}
}
};