Validate Binary Search Tree (LeetCode 98): Solution and Explanation
Given the root of a binary tree, decide whether it is a valid binary search tree. Every value in a node's left subtree must be strictly smaller than the node, every value in its right subtree strictly larger, and both subtrees must themselves be valid BSTs.
Watch it run step by step
Try your own input and write the code →Intuition
The first idea most people try is a local check: at each node, confirm that the left child is smaller and the right child is larger. That is not enough. Consider root 5 with right child 6, and 6 with left child 3. Every parent and child pair looks fine, yet 3 sits in the right subtree of 5, which breaks the rule. The constraint is about whole subtrees, not just immediate children.
So think about what range of values is legal at each position. The root can be anything. When you go left from a node with value v, everything below must be less than v, so v becomes a new upper bound. When you go right, v becomes a new lower bound. As you descend, these bounds only tighten, and each node inherits the constraints of every ancestor on its path.
That turns the problem into a simple DFS that carries an open interval (left, right). A node is fine if its value lies strictly inside the interval, and then you recurse into the left child with the interval (left, node.val) and the right child with (node.val, right). Starting with negative and positive infinity avoids any special case for the root and for values at the extremes of the integer range.
Approach: Recursive DFS with value bounds
- Define
valid(node, left, right), meaning every value in this subtree must lie strictly betweenleftandright. - If
nodeis None, return True because an empty subtree is always valid. - If
node.valis not strictly betweenleftandright, return False. - Recurse left with the upper bound tightened to
node.val, and right with the lower bound raised tonode.val. - Return True only if both subtrees are valid, and start the whole check with
valid(root, float("-inf"), float("inf")).
Step-by-step example
root = [5,4,6,null,null,3,7]
- Check 5 against (-inf, inf). It fits, so recurse into both children.
- Check 4 against (-inf, 5). It fits, and its children are None, so the left subtree is valid.
- Check 6 against (5, inf). It fits, so recurse into its children.
- Check 3 against (5, 6). Since 3 is not greater than 5, the check fails and returns False.
- The False propagates up through 6 and 5, so the tree is not a valid BST, even though 3 is smaller than its own parent 6.
Code: Python, Java, C++
1class Solution:
2 def isValidBST(self, root: Optional[TreeNode]) -> bool:
3 def valid(node, left, right):
4 if not node:
5 return True
6 if not (left < node.val < right):
7 return False
8 return valid(node.left, left, node.val) and valid(node.right, node.val, right)
9
10 return valid(root, float("-inf"), float("inf"))1class Solution {
2 public boolean isValidBST(TreeNode root) {
3 return valid(root, Long.MIN_VALUE, Long.MAX_VALUE);
4 }
5 private boolean valid(TreeNode node, long left, long right) {
6 if (node == null) return true;
7 if (!(node.val > left && node.val < right)) return false;
8 return valid(node.left, left, node.val) && valid(node.right, node.val, right);
9 }
10}1class Solution {
2public:
3 bool isValidBST(TreeNode* root) {
4 return valid(root, LONG_MIN, LONG_MAX);
5 }
6 bool valid(TreeNode* node, long left, long right) {
7 if (!node) return true;
8 if (!(node->val > left && node->val < right)) return false;
9 return valid(node->left, left, node->val) && valid(node->right, node->val, right);
10 }
11};Time and space complexity
O(n)
Each node is checked once against its bounds, with constant work per node. The recursion may stop early on the first violation.
O(h)
The recursion stack grows with the height h of the tree, which is O(log n) when balanced and O(n) when the tree is a chain.
Other approaches
Inorder traversal must be strictly increasing (time O(n), space O(h))
An inorder traversal of a valid BST visits values in strictly increasing order. Traverse inorder, recursively or with a stack, keep the previous value, and fail as soon as the current value is not greater than it.
Subtree min and max postorder (time O(n), space O(h))
Return the minimum and maximum of each subtree from a postorder DFS and check that the node's value is greater than the left max and less than the right min. It works but carries more state than the bounds approach.
Common mistakes
- Only comparing a node with its direct children. That misses violations against higher ancestors, like a small value deep in a right subtree.
- Using non-strict comparisons. Duplicates are not allowed, so a value equal to a bound must fail.
- Starting the bounds at fixed integers such as the 32-bit minimum and maximum. Node values can equal those extremes, so use infinity or None instead.
- Swapping which bound changes when going left versus right. Going left tightens the upper bound and going right raises the lower bound.
Frequently asked questions
Why is checking each node against its children not enough?
The BST rule applies to whole subtrees. A node deep in the right subtree must be larger than every ancestor it passed on the way down by going right, not just larger than its parent, so you need bounds inherited from ancestors.
Can you validate a BST with an inorder traversal?
Yes. A valid BST produces a strictly increasing inorder sequence, so you can traverse inorder while tracking the previous value and fail on any value that is not larger than the one before.
How do you handle values at the integer limits?
Use negative and positive infinity, or None, as the initial bounds. Hardcoding the 32-bit limits fails when a node actually holds one of those values.