Simple C++ recursive approach


#1

TreeNode* sortedBST(const vector &A,int s,int e){
if(s>e) return NULL;
int mid=(s+e)/2;
TreeNode r=new TreeNode(A[mid]);
r->left=sortedBST(A,s,mid-1);
r->right=sortedBST(A,mid+1,e);
return r;
}
TreeNode
Solution::sortedArrayToBST(const vector &A) {
int s=0,e=A.size()-1;
return sortedBST(A,s,e);
}


#2

C++

TreeNode* Solution::sortedArrayToBST(const vector<int> &A) 
{
    if(A.empty())
        return NULL;
    
    unsigned int mid = A.size()/2;
    vector<int> leftArr(A.begin(), A.begin()+mid), rightArr(A.begin()+mid+1, A.end());
    
    TreeNode* head=new TreeNode(A[mid]);
    head->left = sortedArrayToBST(leftArr); head->right = sortedArrayToBST(rightArr);
    
    return head;
}