My solution using recursion


  • 0
    V
    class Solution {
    public:
        TreeNode* sortedArrayToBST(vector<int>& nums) {
            return sortedArrayToBST( nums.begin(), nums.end() );
        }
    
        template<typename inputIterator>
        TreeNode *sortedArrayToBST( inputIterator left, inputIterator right ) {
            if( left == right )
                return nullptr;
        
            auto mid = left + distance( left, right ) / 2;
            auto root = new TreeNode( *mid );
            root->left = sortedArrayToBST( left, mid );
            root->right = sortedArrayToBST( next( mid ), right );
            return root;
        }
    };

Log in to reply
 

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