Sharing my 84ms C++ solution


  • 0
    T
    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    private:
        TreeNode* sortedArrayToBSTHelper(vector<int> nums, int left, int right)
        {
            if(left>right)
                return NULL;
            int middle = left + (right-left)/2;
            TreeNode* tree = new TreeNode(nums[middle]);
            tree->left  = sortedArrayToBSTHelper(nums, left, middle-1);
            tree->right = sortedArrayToBSTHelper(nums, middle+1, right);
            return tree;
        }
    public:
        TreeNode* sortedArrayToBST(vector<int>& nums) {
            int n = nums.size();
            return sortedArrayToBSTHelper(nums, 0, n-1);
        }
    };

Log in to reply
 

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