Validate Binary Search Tree
LeetCode 98 · Medium · solution, intuition & step-by-step walkthrough
Pass (min, max) bounds down the tree.
This is how I solved Validate Binary Search Tree (LeetCode 98), a medium problem from the BST pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
Every node must lie strictly inside a range set by its ancestors: going left tightens the upper bound to the parent's value, going right tightens the lower bound.
Approach
- 1
validate(node, max, min).
- 2
Fail if node.val ≥ max or ≤ min.
- 3
Left child gets max = node.val; right child gets min = node.val.
How I solved it
Range DFSPythonO(n) time · O(h) space
class Solution:
def isValidBST(self, root):
def validateTree(node, mx=None, mn=None):
if mx is not None and node.val >= mx:
return False
if mn is not None and node.val <= mn:
return False
if node.left and not validateTree(node.left, node.val, mn):
return False
if node.right and not validateTree(node.right, mx, node.val):
return False
return True
return validateTree(root)Validate Binary Search Tree — FAQ
What is the intuition behind Validate Binary Search Tree?
Every node must lie strictly inside a range set by its ancestors: going left tightens the upper bound to the parent's value, going right tightens the lower bound.
How do you solve Validate Binary Search Tree (LeetCode 98)?
1. validate(node, max, min). 2. Fail if node.val ≥ max or ≤ min. 3. Left child gets max = node.val; right child gets min = node.val.
What is the time and space complexity of Validate Binary Search Tree?
Time: O(n). Space: O(h). (Accepted approach: Range DFS.)
What are common mistakes in Validate Binary Search Tree?
Comparing only with the direct parent misses violations deeper down (example 2).