File tree Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Original file line number Diff line number Diff line change
1
+ import DS .TreeNode ;
2
+
3
+ /*
4
+ // Definition of TreeNode:
5
+ class TreeNode {
6
+ public int val;
7
+ public TreeNode left;
8
+ public TreeNode right;
9
+ public TreeNode(int val) {
10
+ this.val = val;
11
+ }
12
+ }
13
+ */
14
+
15
+ public class BinarySearchTreeValidation {
16
+ public boolean binarySearchTreeValidation (TreeNode root ) {
17
+ // Start validation at the root node. The root node can contain any
18
+ // value, so set the initial lower and upper bounds to null.
19
+ return isWithinBounds (root , null , null );
20
+ }
21
+
22
+ private boolean isWithinBounds (TreeNode node , Integer lowerBound , Integer upperBound ) {
23
+ // Base case: if the node is null, it satisfies the BST condition.
24
+ if (node == null ) {
25
+ return true ;
26
+ }
27
+ // If the current node's value is not within the valid bounds, this
28
+ // tree is not a valid BST.
29
+ if (lowerBound != null && node .val <= lowerBound || upperBound != null && upperBound <= node .val ) {
30
+ return false ;
31
+ }
32
+ // If the left subtree isn't a BST, this tree isn't a BST.
33
+ if (!isWithinBounds (node .left , lowerBound , node .val )) {
34
+ return false ;
35
+ }
36
+ // Otherwise, return true if the right subtree is also a BST.
37
+ return isWithinBounds (node .right , node .val , upperBound );
38
+ }
39
+ }
You can’t perform that action at this time.
0 commit comments