Accepted C++ solution


  • 0
    P
    class Solution {
    public:
        TreeNode* sortedArrayToBST(vector<int>& nums) {
            if(nums.size() == 0)
                return NULL;
    
            TreeNode* head = solve(nums, 0, nums.size() - 1);
            return head;
        }
        
        TreeNode* solve(vector<int>& nums, int left, int right){
            if(left > right)
                return NULL;
                
            int mid = left + (right - left)/2;
            TreeNode* cur = new TreeNode(nums[mid]);
            cur->left = solve(nums, left, mid - 1);
            cur->right = solve(nums, mid + 1, right);
            return cur;
        }
        
    };
    

Log in to reply
 

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