Skip to content

Commit b0a0ff0

Browse files
committed
Add Binary Search Tree Validation
1 parent 6f7c970 commit b0a0ff0

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import ds.TreeNode
2+
3+
/*
4+
Definition of TreeNode:
5+
6+
data class TreeNode(
7+
var value: Int,
8+
var left: TreeNode? = null,
9+
var right: TreeNode? = null
10+
)
11+
*/
12+
13+
fun binarySearchTreeValidation(root: TreeNode?): Boolean {
14+
// Start validation at the root node. The root node can contain any
15+
// value, so set the initial lower and upper bounds to -infinity and
16+
// +infinity, respectively.
17+
return isWithinBounds(root, Int.MIN_VALUE, Int.MAX_VALUE)
18+
}
19+
20+
fun isWithinBounds(node: TreeNode?, lowerBound: Int, upperBound: Int): Boolean {
21+
// Base case: if the node is null, it satisfies the BST condition.
22+
if (node == null) {
23+
return true
24+
}
25+
// If the current node's value is not within the valid bounds, this
26+
// tree is not a valid BST.
27+
if (node.value <= lowerBound || node.value >= upperBound) {
28+
return false
29+
}
30+
// If the left subtree isn't a BST, this tree isn't a BST.
31+
if (!isWithinBounds(node.left, lowerBound, node.value)) {
32+
return false
33+
}
34+
// Otherwise, return true if the right subtree is also a BST.
35+
return isWithinBounds(node.right, node.value, upperBound)
36+
}

0 commit comments

Comments
 (0)