problems: add „98. Validate Binary Search Tree“
Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
parent
e11a347989
commit
15e6d58b12
1 changed files with 26 additions and 0 deletions
26
problems/validate-binary-search-tree.kt
Normal file
26
problems/validate-binary-search-tree.kt
Normal file
|
@ -0,0 +1,26 @@
|
||||||
|
/**
|
||||||
|
* 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())
|
||||||
|
}
|
Loading…
Reference in a new issue