File tree Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments