Problem 98

Abstract / Summary

Check if a binary tree follows the rules that all left values are less than the node and all right values are greater.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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"))
18 lines | 530 bytes | submitted August 17, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

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
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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 root is None, check returns True, 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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 8 | μ = 8.04 | σ = 0.81

Complexity Analysis

Time: linear
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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++
61 links | 44 authors | 12 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Validate Binary Search Tree - Depth First Search - Leetcode 98'
NeetCode 10 mins
Validate Binary Search Tree - Depth First Search - Leetcode 98
YouTube video 'Validate Binary Search Tree (LeetCode 98) | Full solution with animations and visuals'
Nikhil Lohia 17 mins
Validate Binary Search Tree (LeetCode 98) | Full solution with animations and visuals
YouTube video 'Is Binary Tree A BST Using Inorder Property | Leetcode 98. Validate Binary Search Tree Solution'
Pepcoding 21 mins
Is Binary Tree A BST Using Inorder Property | Leetcode 98. Validate Binary Search Tree Solution
YouTube video 'LeetCode 98. Validate Binary Search Tree - Interview Prep Ep 69'
Fisher Coder 10 mins
LeetCode 98. Validate Binary Search Tree - Interview Prep Ep 69
YouTube video 'Validate Binary Search Tree | Live Coding with Explanation | Leetcode - 98'
Algorithms Made Easy 5 mins
Validate Binary Search Tree | Live Coding with Explanation | Leetcode - 98
YouTube video 'Validate Binary Search Tree - LeetCode 98 - JavaScript'
AlgoJS 6 mins
Validate Binary Search Tree - LeetCode 98 - JavaScript
YouTube video 'Validate Binary Search Tree - LeetCode 98 - Python'
Deepti Talesra 18 mins
Validate Binary Search Tree - LeetCode 98 - Python
YouTube video '[Java] Leetcode 98. Validate Binary Search Tree [Binary Search Tree #3]'
Eric Programming 12 mins
[Java] Leetcode 98. Validate Binary Search Tree [Binary Search Tree #3]
YouTube video 'Validate Binary Search Tree - LeetCode 98 - Coding Interview Questions'
One Code Man 4 mins
Validate Binary Search Tree - LeetCode 98 - Coding Interview Questions
YouTube video 'Validate Binary Search Tree | Leetcode 98'
Knowledge Center 20 mins
Validate Binary Search Tree | Leetcode 98
YouTube video 'VALIDATE BINARY SEARCH TREE | LEETCODE # 98 | PYTHON POSTORDER DFS SOLUTION'
Cracking FAANG 19 mins
VALIDATE BINARY SEARCH TREE | LEETCODE # 98 | PYTHON POSTORDER DFS SOLUTION
YouTube video '98. Validate Binary Search Tree | JavaScript | DFS | Depth First Search | Easy Explanation'
LeetCodeWithMonu 12 mins
98. Validate Binary Search Tree | JavaScript | DFS | Depth First Search | Easy Explanation
YouTube video '98. Validate Binary Search Tree | Day 023 | 2 Ways | Limit Ranges | Inorder Traversal'
Aryan Mittal 20 mins
98. Validate Binary Search Tree | Day 023 | 2 Ways | Limit Ranges | Inorder Traversal
YouTube video 'Leetcode 98 Validate Binary Search Tree (Java)'
TheAnalyticGuy 9 mins
Leetcode 98 Validate Binary Search Tree (Java)
YouTube video 'Validate Binary Search Tree |BST 2 | Placement Preparation Series | LeetCode 98 | Medium ||'
Bro Coders 11 mins
Validate Binary Search Tree |BST 2 | Placement Preparation Series | LeetCode 98 | Medium ||
YouTube video 'Validate Binary Search Tree | Leetcode 98 | December Leetcode challenge Day 16'
Coding Decoded 9 mins
Validate Binary Search Tree | Leetcode 98 | December Leetcode challenge Day 16
YouTube video 'Daily Leetcode #863: Aug 11, 2022 - 98. Validate Binary Search Tree'
Programming Live with Larry 12 mins
Daily Leetcode #863: Aug 11, 2022 - 98. Validate Binary Search Tree
YouTube video 'Daily Leetcode #260: Dec 16, 2020 - 98. Validate Binary Search Tree'
Programming Live with Larry 11 mins
Daily Leetcode #260: Dec 16, 2020 - 98. Validate Binary Search Tree
YouTube video '30. Leetcode 98. Validate Binary Search Tree : JAVA'
Web Fusion with Bharadwaj 15 mins
30. Leetcode 98. Validate Binary Search Tree : JAVA
YouTube video 'Day 244: LeetCode Problem 98. Validate Binary Search Tree - Swift'
iOSxBank 12 mins
Day 244: LeetCode Problem 98. Validate Binary Search Tree - Swift
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

2 similar problems

Solved On The Same Day

1 easy 12 medium 3 hard
17 solutions   August 17, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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