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.

Revisions

  1. ZviMints created this gist Mar 19, 2021.
    27 changes: 27 additions & 0 deletions isValidBST.scala
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,27 @@
    // 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)
    }
    }