Skip to content

Instantly share code, notes, and snippets.

@ZviMints
Created March 19, 2021 20:29
Show Gist options
  • Select an option

  • Save ZviMints/bc2077f2b55ff32327cd0fc359de6fc0 to your computer and use it in GitHub Desktop.

Select an option

Save ZviMints/bc2077f2b55ff32327cd0fc359de6fc0 to your computer and use it in GitHub Desktop.
Checks if BST is valid
// https://leetcode.com/problems/validate-binary-search-tree/
class TreeNode(_value: Int = 0, _left: TreeNode = null, _right: TreeNode = null) {
var value: Int = _value
var left: TreeNode = _left
var right: TreeNode = _right
}
object Solution {
def isValidBST(root: TreeNode): Boolean = {
implicit class isBetween(curr: TreeNode) {
def isBetween(from: Long, to: Long) = curr.value > from && curr.value < to
}
def go(root: TreeNode, from: Long, to: Long): Boolean = {
if(root == null) true
else {
root.isBetween(from, to) &&
go(root.left, from, root.value) &&
go(root.right, root.value, to)
}
}
go(root, Long.MinValue, Long.MaxValue)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment