An C++ OOP-style solution


  • 0
    L
    class Solution {
    private:
        struct SolutionImpl {
            const vector<int>& nums;
            SolutionImpl(const vector<int>& nums) : nums(nums) {}
            TreeNode* solve(size_t l, size_t r) {
                if (l >= r)
                    return nullptr;
                size_t m = (l + r) / 2; // overflow possible, but who cares?
                auto ans = new TreeNode(nums[m]);
                ans->left = solve(l, m);
                ans->right = solve(m + 1, r);
                return ans;
            }
        };
    public:
        TreeNode* sortedArrayToBST(vector<int>& nums) {
            return SolutionImpl(nums).solve(0, nums.size());
        }
    };
    

Log in to reply
 

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