Introduction
Validate BST means:
- checking whether
a binary tree
follows BST rules
BST Property:
Left subtree values < Root value < Right subtree valuesEvery node must:
- satisfy valid range
- maintain BST ordering
Example:
5/ \
3 7
/ \ / \
2 4 6 8
Output:
True
Invalid Example:
5/ \
3 7
/
4
Output:
False
Explanation:
4 exists inside right subtree of 5 but is smaller than 5. This problem is one of the most important applications of:
DFS Traversal Constraints
1 <= Number of Nodes <= 10^5 Approach : Recursive DFS Range Validation
Explanations:
Explanation:
The idea is:
- recursively validate nodes
using minimum and maximum limits
Steps:
- Visit current node.
- Check valid range.
- Update maximum for left subtree.
- Update minimum for right subtree.
- Recursively validate subtrees.
Conditions:
minimum < node.value < maximum Left subtree:
maximum = current node value Right subtree:
minimum = current node value This approach:
- uses DFS recursion
- validates BST ordering globally
Dry Run
Visit:5
Range:
(-∞, +∞)
Visit:
3
Range:
(-∞, 5)
Visit:
7
Range:
(5, +∞)
All nodes satisfy BST rules.
Tree is valid.
Practice :