Skip to content

Commit 06d77e2

Browse files
committed
Validate Binary Search Tree
1 parent 5f4e52a commit 06d77e2

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
// TC: O(n)
2+
// visit all nodes to compare
3+
// SC: O(n)
4+
// recursion requires O(n) SC in the worst case
5+
class Solution {
6+
public boolean isValidBST(TreeNode root) {
7+
return dfs(root, Long.MIN_VALUE, Long.MAX_VALUE);
8+
}
9+
10+
private boolean dfs(TreeNode node, long min, long max) {
11+
if (node == null) return true;
12+
13+
if (node.val <= min || node.val >= max) return false;
14+
return dfs(node.left, min, node.val) &&
15+
dfs(node.right, node.val, max);
16+
}
17+
}

0 commit comments

Comments
 (0)