Python 0098.py
class Solution:
def check(self, root, minn, maxx):
if not root:
return True
if root.val <= minn:
return False
if root.val >= maxx:
return False
if not self.check(root.left, minn, root.val):
return False
if not self.check(root.right, root.val, maxx):
return False
return True
def isValidBST(self, root: Optional[TreeNode]) -> bool:
return self.check(root, float("-inf"), float("+inf"))
Difficulty
and has an acceptance rate of about 36% (9+ million submissions).
Typical patterns to solve this problem:
- Binary Search Tree
- Binary Tree
- Depth First Search
- Tree
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation defines a class Solution that validates whether a binary tree satisfies the properties of a binary search tree (BST). The core logic resides in a recursive helper method check that traverses the tree while maintaining lower and upper bounds for each node’s value. The public method isValidBST initializes the recursion with infinite bounds and returns the final boolean result.
Key Functions
Recursive Validation (check)
def check(self, root, minn, maxx):
if not root:
return True
if root.val <= minn:
return False
if root.val >= maxx:
return False
if not self.check(root.left, minn, root.val):
return False
if not self.check(root.right, root.val, maxx):
return False
return True
The check function receives a node reference together with the current permissible minimum (minn) and maximum (maxx) values. It first handles the base case where the node is None, indicating a leaf’s child, and returns True. The next two conditional statements enforce the BST ordering: a node’s value must be strictly greater than the lower bound and strictly less than the upper bound. If either condition fails, the function returns False immediately, short-circuiting further traversal.
The recursive calls propagate updated bounds down the left and right subtrees. For the left child, the upper bound becomes the current node’s value, while the lower bound remains unchanged. For the right child, the lower bound becomes the current node’s value, while the upper bound stays the same. Each recursive invocation returns a boolean, and any False result aborts the remaining checks.
Public Interface (isValidBST)
def isValidBST(self, root: Optional[TreeNode]) -> bool:
return self.check(root, float("-inf"), float("+inf"))
The entry point supplies the initial bounds as negative and positive infinity, ensuring that the root node is unrestricted by external constraints. The method simply forwards the result of check to the caller.
Edge Cases Handled
The algorithm explicitly addresses several edge conditions:
- Empty Tree - When
rootisNone,checkreturnsTrue, correctly treating an empty tree as a valid BST. - Duplicate Values - The strict inequality checks (
<=for the lower bound and>=for the upper bound) reject nodes whose value equals either bound. This prevents trees with duplicate keys from being considered valid BSTs, adhering to the conventional definition that requires distinct values. - Extreme Integer Values - By initializing bounds with floating-point infinities, the code safely accommodates nodes whose values are at the limits of integer representation without overflow or underflow concerns.
- Deeply Nested Structures - The recursive design naturally descends to any depth, and the early return on violation ensures that the function does not continue traversing once an invalid condition is detected.
Performance Considerations
The implementation achieves optimal traversal efficiency by visiting each node exactly once. The early exit strategy-returning False as soon as a bound violation is detected-prevents unnecessary exploration of subtrees that are already known to be invalid. This pruning effect reduces the total number of recursive calls in cases where the tree fails the BST property near the top.
Using floating-point infinities for the initial bounds eliminates the need for special sentinel values or additional checks for integer overflow, simplifying the comparison logic and keeping the per-node overhead minimal. The recursion depth corresponds to the height of the tree, and the function relies on the language’s call stack without allocating auxiliary data structures, thereby maintaining a low memory footprint.
Overall, the code presents a concise and effective solution for BST validation, leveraging recursive bound propagation and early termination to ensure both correctness and efficiency.
ELI5 - Simplified Explanation
Imagine a tree made of numbers where every branch follows a special rule. At the very top, there is a number. Everything to the left must be smaller than that number, and everything to the right must be bigger.
The code works like a helper that visits every spot in the tree to make sure the rule is always followed. When the helper visits a spot, it carries two notes. The first note tells the helper the smallest number allowed, and the second note tells the helper the biggest number allowed.
If the helper reaches a spot where the number is too small or too big, it knows the tree is broken. If the helper goes to the left, it shrinks the allowed size because the next numbers must be smaller than the current one. If the helper goes to the right, it shrinks the allowed size the other way because the numbers must be bigger. The helper keeps checking every branch until it has looked at all of them. If the helper makes it through the whole tree without finding any broken rules, that means the tree is perfectly organized.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||||||
| WalkCCC | C++ | Python | Java | ||||||||||
| leetcode.ca | C++ | Python | C# | Java | Rust | JS | Go | TS | |||||
| LeetcodeHelp | C++ | Python | Java | ||||||||||
| MemoryLimitExceeded | C++ | Python | |||||||||||
| Progiez | C++ | Python | Java | ||||||||||
| github | AdelDaniel | Dart | |||||||||||
| aylei | Rust | ||||||||||||
| begeekmyfriend | C | ||||||||||||
| BigEggStudy | C# | ||||||||||||
| black-shadows | C++ | ||||||||||||
| bujosa | Python | ||||||||||||
| chandansgowda | Python | ||||||||||||
| charles-wangkai | Java | ||||||||||||
| chenyanzhe | C++ | ||||||||||||
| everthis | JS | ||||||||||||
| fartem | Ruby | ||||||||||||
| FelixFan1122 | C# | ||||||||||||
| fengvyi | C++ | ||||||||||||
| gaosq0604 | Python | ||||||||||||
| Garvit244 | Python | ||||||||||||
| halfrost | Go | ||||||||||||
| haoel | C++ | ||||||||||||
| JoshCrozier | JS | ||||||||||||
| keineahnung2345 | C++ | ||||||||||||
| Krazune | C++ | ||||||||||||
| lennylxx | C | ||||||||||||
| linouk23 | C++ | ||||||||||||
| lkwq007 | Python | ||||||||||||
| luangong | C++ | ||||||||||||
| MacJim | C++ | ||||||||||||
| qiyuangong | Python | ||||||||||||
| ruoru | Rust | ||||||||||||
| shreymehul | C# | ||||||||||||
| sonugiri1043 | C++ | ||||||||||||
| suxrobGM | C# | ||||||||||||
| varunu28 | Java | ||||||||||||
| vli02 | C | ||||||||||||
| vthwang | Java | ||||||||||||
| wisdompeak | C++ | ||||||||||||
| XiaotaoGuo | C++ | ||||||||||||
| yuanliu666 | Kotlin | ||||||||||||
| YuriSpiridonov | Python | ||||||||||||
| zfang399 | C++ | ||||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||||
| WalkCCC | C++, Python, Java | ||||||||||||
| leetcode.ca | C++, C#, Go, Java, JavaScript, Python, Rust, TypeScript | ||||||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||||||
| MemoryLimitExceeded | Python, C++ | ||||||||||||
| Progiez | C++, Java, Python | ||||||||||||
| AdelDaniel | Dart | ||||||||||||
| aylei | Rust | ||||||||||||
| begeekmyfriend | C | ||||||||||||
| BigEggStudy | C# | ||||||||||||
| black-shadows | C++, C++ | ||||||||||||
| bujosa | Python | ||||||||||||
| chandansgowda | Python | ||||||||||||
| charles-wangkai | Java | ||||||||||||
| chenyanzhe | C++ | ||||||||||||
| everthis | JavaScript | ||||||||||||
| fartem | Ruby | ||||||||||||
| FelixFan1122 | C# | ||||||||||||
| fengvyi | C++ | ||||||||||||
| gaosq0604 | Python | ||||||||||||
| Garvit244 | Python | ||||||||||||
| halfrost | Go | ||||||||||||
| haoel | C++ | ||||||||||||
| JoshCrozier | JavaScript | ||||||||||||
| keineahnung2345 | C++ | ||||||||||||
| Krazune | C++ | ||||||||||||
| lennylxx | C | ||||||||||||
| linouk23 | C++ | ||||||||||||
| lkwq007 | Python | ||||||||||||
| luangong | C++ | ||||||||||||
| MacJim | C++ | ||||||||||||
| qiyuangong | Python | ||||||||||||
| ruoru | Rust | ||||||||||||
| shreymehul | C# | ||||||||||||
| sonugiri1043 | C++ | ||||||||||||
| suxrobGM | C# | ||||||||||||
| varunu28 | Java | ||||||||||||
| vli02 | C | ||||||||||||
| vthwang | Java | ||||||||||||
| wisdompeak | C++ | ||||||||||||
| XiaotaoGuo | C++ | ||||||||||||
| yuanliu666 | Kotlin | ||||||||||||
| YuriSpiridonov | Python | ||||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 94: Binary Tree Inorder Traversal
- problem 501: Find Mode in Binary Search Tree
Solved On The Same Day
- problem 195: Tenth Line
- problem 53: Maximum Subarray
- problem 56: Merge Intervals
- problem 78: Subsets
- problem 86: Partition List
- problem 89: Gray Code
- problem 90: Subsets II
- problem 179: Largest Number
- problem 456: 132 Pattern
- problem 473: Matchsticks to Square
- problem 542: 01 Matrix
- problem 916: Word Subsets
- problem 1930: Unique Length-3 Palindromic Subsequences
- problem 233: Number of Digit One
- problem 295: Find Median from Data Stream
- problem 315: Count of Smaller Numbers After Self
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality