My 19ms C++ Recursive Solution


  • 0
    W
    class Solution {
        public:
            TreeNode* sortedArrayToBST(vector<int>& nums) {
                if (nums.size() == 0) return nullptr;
                int mid = nums.size() / 2;
                TreeNode *node = new TreeNode(nums[mid]);
                auto leftTree = vector<int>(nums.begin(), nums.begin() + mid);
                auto rightTree = vector<int>(nums.begin() + mid + 1, nums.end());
                if (mid != 0)
                    node->left = sortedArrayToBST(leftTree);
                if (mid != nums.size() - 1) 
                    node->right = sortedArrayToBST(rightTree);
                return node;
            }
    };
    

Log in to reply
 

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