Created
July 23, 2018 03:46
-
-
Save ekeitho/0aa7c810e617b99748b97c4a433d92a5 to your computer and use it in GitHub Desktop.
validate bst
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
@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