Ruby: `new': stack level too deep (SystemStackError)


  • 0
    F

    My code doesn't work,

    def sorted_array_to_bst(nums)
        node = TreeNode.new(2)
        return nil if nums == nil || nums == [] 
        
        return TreeNode.new(nums[0]) if nums.size == 1
        node = TreeNode.new(0)
    
        mid = nums.size / 2
        node.val = nums[mid]
        node.left = sorted_array_to_bst(nums[0..mid])
        node.right = sorted_array_to_bst(nums[mid...nums.size])
    
        return node
    end
    

    However this works...

    def sorted_array_to_bst(nums)
        node = TreeNode.new(2)
        return node
    end

  • 0
    H

    left side always gets mid node.
    try node.right = sorted_array_to_bst(nums[mid + 1 ..nums.size])


Log in to reply
 

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