Skip to content

Instantly share code, notes, and snippets.

@ekeitho
Created July 23, 2018 03:46
Show Gist options
  • Save ekeitho/0aa7c810e617b99748b97c4a433d92a5 to your computer and use it in GitHub Desktop.
Save ekeitho/0aa7c810e617b99748b97c4a433d92a5 to your computer and use it in GitHub Desktop.
validate bst
@Test
fun test() {
val n = BinaryNode(4)
.apply {
addLeft(2).apply {
addLeft(1)
}
addRight(6).apply {
addRight(7)
}
}
assert(validateBst1(n))
assert(validateBst2(n, Int.MIN_VALUE, Int.MAX_VALUE))
n.addLeft(10)
assert(validateBst2(n, Int.MIN_VALUE, Int.MAX_VALUE) == false)
}
fun validateBst1(node: BinaryNode<Int>?): Boolean {
if (node == null) return true
if (node.left == null && node.right == null) return true;
var left : Boolean = false
var right: Boolean = false
if (node.left == null || node.data >= node.left!!.data) {
left = validateBst1(node.left)
}
if (node.right == null || node.data <= node.right!!.data) {
right = validateBst1(node.right)
}
return left && right
}
fun validateBst2(node: BinaryNode<Int>?, min: Int, max: Int): Boolean {
if (node == null) return true
if (node.data !in min..max) return false
return validateBst2(node.left, min, node.data) && validateBst2(node.right, node.data, max)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment