Skip to content

Commit 97f179c

Browse files
solves validate bst in java
1 parent b1e0d04 commit 97f179c

File tree

2 files changed

+18
-1
lines changed

2 files changed

+18
-1
lines changed

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,7 @@
8989
| 95 | [Unique Binary Search Trees II](https://leetcode.com/problems/unique-binary-search-trees-ii) | [![Java](assets/java.png)](src/UniqueBinarySearchTreesII.java) | |
9090
| 96 | [Unique Binary Search Trees](https://leetcode.com/problems/unique-binary-search-trees) | [![Java](assets/java.png)](src/UniqueBinarySearchTrees.java) | |
9191
| 97 | [Interleaving String](https://leetcode.com/problems/interleaving-string) | | |
92-
| 98 | [Validate Binary Search Tree](https://leetcode.com/problems/validate-binary-search-tree) | | |
92+
| 98 | [Validate Binary Search Tree](https://leetcode.com/problems/validate-binary-search-tree) | [![Java](assets/java.png)](src/ValidateBinarySearchTree.java) | |
9393
| 99 | [Recover Binary Search Tree](https://leetcode.com/problems/recover-binary-search-tree) | | |
9494
| 100 | [Same Tree](https://leetcode.com/problems/same-tree) | [![Java](assets/java.png)](src/SameTree.java) [![Python](assets/python.png)](python/same_tree.py) | |
9595
| 101 | [Symmetric Tree](https://leetcode.com/problems/symmetric-tree) | [![Java](assets/java.png)](src/SymmetricTree.java) [![Python](assets/python.png)](python/symmetric_tree.py) | |

src/ValidateBinarySearchTree.java

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
// https://leetcode.com/problems/validate-binary-search-tree
2+
// T: O(n)
3+
// S: O(log(n))
4+
5+
public class ValidateBinarySearchTree {
6+
public boolean isValidBST(TreeNode root) {
7+
return isValidBST(root, Long.MIN_VALUE, Long.MAX_VALUE);
8+
}
9+
10+
private boolean isValidBST(TreeNode root, long minLeftVal, long maxRightVal) {
11+
if (root == null) return true;
12+
return minLeftVal < root.val
13+
&& root.val < maxRightVal
14+
&& isValidBST(root.left, minLeftVal, root.val)
15+
&& isValidBST(root.right, root.val, maxRightVal);
16+
}
17+
}

0 commit comments

Comments
 (0)