Easy to understand C++ recursive solution 20ms


  • 0
    M
    TreeNode* getNode(vector<int>& nums, int left, int right) {
            if (left > right || left < 0 || right == nums.size()) {
                return NULL;
            }
            int mid = left + (right - left) / 2;
            TreeNode* root = new TreeNode(nums[mid]);
            root -> left = getNode(nums, left, mid-1);
            root -> right = getNode(nums, mid+1, right);
            return root;
            
        }
        TreeNode* sortedArrayToBST(vector<int>& nums) {
            return getNode(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.