2022-08-11 10:02:47 +02:00
|
|
|
/**
|
|
|
|
* 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) {
|
2024-05-17 18:23:38 +02:00
|
|
|
fun check(x: Int): Boolean = (min == null || x > min) && (max == null || x < max)
|
2022-08-11 10:02:47 +02:00
|
|
|
}
|
|
|
|
|
2024-05-17 18:23:38 +02:00
|
|
|
private fun isValidBST(
|
|
|
|
root: TreeNode?,
|
|
|
|
range: SpecialRange,
|
|
|
|
): Boolean =
|
2022-08-11 10:02:47 +02:00
|
|
|
when (root) {
|
|
|
|
null -> true
|
2024-05-17 18:23:38 +02:00
|
|
|
else ->
|
|
|
|
range.check(root.`val`) &&
|
|
|
|
isValidBST(root.left, range.copy(max = root.`val`)) &&
|
|
|
|
isValidBST(root.right, range.copy(min = root.`val`))
|
2022-08-11 10:02:47 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
fun isValidBST(root: TreeNode?): Boolean = isValidBST(root, SpecialRange())
|
|
|
|
}
|