Created
March 19, 2021 20:29
-
-
Save ZviMints/bc2077f2b55ff32327cd0fc359de6fc0 to your computer and use it in GitHub Desktop.
Checks if BST is valid
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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