Recursive C++ Approach, All Improvisations are Welcome!


#1
/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
TreeNode* Solution::sortedArrayToBST(const vector<int> &A) 
{
    if(A.size() == 0)
        return NULL;
    if(A.size() == 1)
    {
        TreeNode *root = new TreeNode(A[0]);
        return root;
    }
    
    int mid = A.size() / 2;
    TreeNode *root = new TreeNode(A[mid]);
    vector<int> left(A.begin(),A.begin()+mid);
    vector<int> right(A.begin()+mid+1,A.end());
    root->left = sortedArrayToBST(left);
    root->right = sortedArrayToBST(right);
    
    return root;
}