LeetCode 98: Validate Binary Search Tree is a Medium binary search tree problem. This Python walkthrough develops a recursive value bounds solution, ties every code decision to a concrete invariant, and includes the regression check used before publication.
This independent guide paraphrases the task rather than reproducing LeetCode’s prompt. Use the official page for the exact statement, examples, constraints, and submission runner.
| Difficulty | Medium |
|---|---|
| Topic | Binary Search Tree |
| Reusable pattern | recursive value bounds |
| Complexity | O(n) time and O(h) recursion space |
Recognizing the pattern
BST ordering turns inorder traversal into a sorted stream and lets inherited bounds rule out whole subtrees.
For this problem specifically, pass strict lower and upper bounds into each subtree; every node must lie inside its inherited interval. The invariant worth writing beside the code is: The bounds represent every ancestor constraint that applies to the current subtree.
Step-by-step algorithm
- Identify the input state consumed by
isValidBST(root)and initialize the data required by the recursive value bounds pattern. - Pass strict lower and upper bounds into each subtree; every node must lie inside its inherited interval.
- After each update, verify the page’s central invariant: The bounds represent every ancestor constraint that applies to the current subtree.
- Finish only after the boundary behavior is covered: Duplicates are invalid because inequalities are strict.
Python solution
LeetCode supplies the list, tree, or graph node class referenced by this method. The downloadable test suite includes compatible local node definitions so the implementation can also run outside the judge.
class Solution:
def isValidBST(self, root):
def valid(node, lower, upper):
if not node: return True
if not lower < node.val < upper: return False
return valid(node.left, lower, node.val) and valid(node.right, node.val, upper)
return valid(root, float("-inf"), float("inf"))Reading the implementation
The main entry point is isValidBST(root). The implementation keeps little named state because each operation can be resolved directly from the current input position.
The method expresses the transformation directly without a general traversal loop. Early returns stop as soon as the answer is forced, avoiding work that cannot change the result. In concrete terms, pass strict lower and upper bounds into each subtree; every node must lie inside its inherited interval.
Correctness argument
Base case. Empty or terminal subproblems return a result that already satisfies the claim for that smallest state.
Inductive step. Pass strict lower and upper bounds into each subtree; every node must lie inside its inherited interval. Assuming child or smaller states are correct, the current call combines only results allowed by the problem, so the bounds represent every ancestor constraint that applies to the current subtree.
Conclusion. Every recursive call reduces the remaining state. The base cases terminate, and induction carries the invariant back to the original input, establishing the returned answer.
Complexity and trade-offs
O(n) time and O(h) recursion space. The auxiliary-space figure excludes the returned output unless the output itself is the structure being built.
Collecting all values and sorting works for a general tree, but it ignores the ordering guarantee and uses extra time or space. That comparison is useful in an interview because it explains why the final implementation is preferable, not merely that it passes.
Regression check
The published implementation belongs to a 100-problem suite that is compiled and exercised behaviorally before deployment.
One reference assertion from that suite is shown below. It targets the normal path while the edge conditions in the next section cover the failure-prone boundaries.
assert Solution().isValidBST(bst) and not Solution().isValidBST(tree([5,1,4,None,None,3,6]))Common mistakes and edge cases
- Problem-specific boundary: Duplicates are invalid because inequalities are strict.
- Pattern-level pitfall: Use strict bounds when duplicates are invalid and avoid numeric sentinels that conflict with legitimate negative values.
- Invariant check: after every update, confirm that the bounds represent every ancestor constraint that applies to the current subtree.
Interview review checklist
- Explain why recursive value bounds matches the structure of this input.
- State the invariant in one sentence before tracing code: The bounds represent every ancestor constraint that applies to the current subtree.
- Derive O(n) time and O(h) recursion space from how many times each element or state is visited.
- Test the boundary explicitly: Duplicates are invalid because inequalities are strict.
Browse the searchable 100 LeetCode Python Solutions hub. Previous: 230. Kth Smallest Element in a BST · Next: 200. Number of Islands