Easy and fast 20 ms


  • 0
    W
    class Solution {
    public:
        TreeNode* convert(vector<int>& nums, int i1, int i2) {
            if( i1 == i2 ) {
                TreeNode* r = new TreeNode( nums[i1] );
                return r;
            }
            else {
                int m = ( i1 + i2 ) / 2;
                TreeNode* r = new TreeNode( nums[m] );
                if( m > i1 ) r->left = convert( nums, i1, m - 1 );
                if( m < i2 ) r->right = convert( nums, m + 1, i2 );
                
                return r;
            }
        }
    
        TreeNode* sortedArrayToBST(vector<int>& nums) {
            if( nums.empty() )
                return 0;
            else 
                return convert( nums, 0, nums.size() - 1 );
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.