1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-11-14 09:59:41 +01:00
LeetCode/kt/validate-binary-search-tree.kt

27 lines
819 B
Kotlin
Raw Normal View History

/**
* Example:
* var ti = TreeNode(5)
* var v = ti.`val`
* Definition for a binary tree node.
* class TreeNode(var `val`: Int) {
* var left: TreeNode? = null
* var right: TreeNode? = null
* }
*/
class Solution {
private data class SpecialRange(val min: Int? = null, val max: Int? = null) {
fun check(x: Int): Boolean =
(min == null || x > min) && (max == null || x < max)
}
private fun isValidBST(root: TreeNode?, range: SpecialRange): Boolean =
when (root) {
null -> true
else -> range.check(root.`val`)
&& isValidBST(root.left, range.copy(max=root.`val`))
&& isValidBST(root.right, range.copy(min=root.`val`))
}
fun isValidBST(root: TreeNode?): Boolean = isValidBST(root, SpecialRange())
}