oday
02/01/2021, 2:39 PMclass Solution(object):
def _isValidBSTHelper(self, n, low, high):
if not n:
return True
val = n.val
if ((val > low and val < high) and
self._isValidBSTHelper(n.left, low, n.val) and
self._isValidBSTHelper(n.right, n.val, high)):
return True
return False
def isValidBST(self, n):
return self._isValidBSTHelper(n, float('-inf'), float('inf'))
my attempt produced this
fun isValidChecker(
node: Node<Int>?, low: Int, high: Int
): Boolean {
if (node == null)
return true
val value = node.value
if (value in (low + 1) until high
&& isValidChecker(node.left, low, value)
&& isValidChecker(node.right, value, high)
)
return true
return false
}
fun isValidBST(node: Node<Int>?): Boolean {
return isValidChecker(
node, Int.MIN_VALUE, Int.MAX_VALUE
)
}
Ruckus
02/01/2021, 3:53 PMfun Node<Int>?.isValidBST(
low: Int = Int.MIN_VALUE,
hight: Int = Int.MAX_VALUE,
): Boolean = return this == null ||
value in (low + 1) until high &&
left.isValidBST(low, value) &&
right.isValidBST(value, high)
oday
02/01/2021, 3:53 PMRuckus
02/01/2021, 3:55 PModay
02/01/2021, 3:55 PMRuckus
02/01/2021, 3:57 PMfun Node<Int>?.isValidBST(
low: Int = Int.MIN_VALUE,
hight: Int = Int.MAX_VALUE,
): Boolean = this == null ||
value <= low &&
value >= high &&
left.isValidBST(low, value - 1) &&
right.isValidBST(value + 1, high)
oday
02/01/2021, 4:02 PMRuckus
02/01/2021, 4:05 PMval value = node.value.toDouble()
And accepting Doubles
for the low / high params, using Double.NEGATIVE_INFINITY
and Double.POSITIVE_INFINITY
as the initial bounds.oday
02/01/2021, 4:45 PMclass Solution {
fun TreeNode?.isValidBST(
low: Double = Double.NEGATIVE_INFINITY, high: Double = Double.POSITIVE_INFINITY
): Boolean = this == null ||
(`val`.toDouble() > low && `val`.toDouble() < high)
&& left.isValidBST(low, `val`.toDouble())
&& right.isValidBST(`val`.toDouble(), high)
fun isValidBST(root: TreeNode?): Boolean {
return root.isValidBST()
}
}