Validate Binary Search Tree
mediumBlind 75NeetCode 150treesbstrecursion
Problem
Given the root of a binary tree, decide whether it is a valid binary search tree, meaning every node's value is greater than all values in its left subtree and smaller than all in its right subtree.
Examples
Input: [2, 1, 3]
Output: true
Left child smaller, right child larger.
Input: [5, 1, 4, null, null, 3, 6]
Output: false
The value 3 violates the upper bound set by its ancestors.
Constraints
- • 1 <= number of nodes <= 10^4
- • -2^31 <= node value <= 2^31 - 1
Hints(tap to reveal)
- 1. Comparing only direct children is not enough.
- 2. Pass down an allowed value range to each node.
Optimal approach(spoiler)
- Recurse with a lower and upper bound, initially unbounded.
- Each node's value must lie strictly within its bounds.
- Recurse left with the node's value as the new upper bound.
- Recurse right with the node's value as the new lower bound.
- O(n) time, O(h) space.
Ready to solve it?
Write your solution in the editor and get an instant AI grade on correctness, edge cases, and complexity.
Practice in the editor