Skip to content

Bug Report for valid-binary-search-tree #6153

Description

@nvd916

Bug Report for https://neetcode.io/problems/valid-binary-search-tree

Please describe the bug below and include any steps to reproduce the bug or screenshots if possible.

Got StackOverFlowError. This code runs fine on LeetCode.

Image Image

The code (Kotlin):

/**
 * Definition for a binary tree node.
 * class TreeNode(var `val`: Int) {
 *     var left: TreeNode? = null
 *     var right: TreeNode? = null
 * }
 */

class Solution {
    fun isValidBST(root: TreeNode?): Boolean {
        fun isValid(node: TreeNode, upBound: Int?, lowBound: Int?): Boolean = with(node) {
            val newUpBound = upBound?.let { minOf(it, `val`) } ?: `val`
            val newLowBound = lowBound?.let { maxOf(it, `val`) } ?: `val`
            if (left == null && right == null) return true
            if (right == null) 
                return left!!.`val` < newUpBound 
                    && (lowBound == null || left!!.`val` > lowBound) 
                    && isValid(left!!, newUpBound, lowBound)
            val rightValid = right!!.`val` > newLowBound && (upBound == null || right!!.`val` < upBound)
            if (left == null) return rightValid && isValid(right!!, upBound, newLowBound)
            val leftValid = left!!.`val` < newUpBound && (lowBound == null || left!!.`val` > lowBound)
            return leftValid && rightValid && isValid(left!!, newUpBound, lowBound) && isValid(right!!, upBound, newLowBound)
        }
        return isValid(root!!, null, null)
    }
}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions