Skip to content

Commit 434c1c8

Browse files
committed
add: BinarySearchTreeValidation, use null to replace float('-inf') and float('inf') in python solution
1 parent 7bf950b commit 434c1c8

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
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+
}

0 commit comments

Comments
 (0)