Data Structures · Visualization
BST: Validate
Binary Search Tree
Validating a BST checks that every node's value falls within the valid (min, max) bound inherited from its ancestors — a node isn't valid just because it's greater than its immediate parent's left child or less than its right child; the constraint must hold against every ancestor along the path. Time: O(n). Space: O(h) recursion stack.
Big-O: Search/insert/delete O(log n) on a balanced tree, O(n) worst case.
BST: Validate
Binary Search TreeValidating a BST checks that every node's value falls within the valid (min, max) bound inherited from its ancestors — a node isn't valid just because it's greater than its immediate parent's left child or less than its right child; the constraint must hold against every ancestor along the path.
How Validate Works
- Start a recursive check at the root with bounds (-infinity, +infinity).
- At each node, verify its value is strictly within the current (min, max) bounds; if not, the tree is invalid.
- Recurse into the left child with bounds (min, node.value) — everything left must stay below this node.
- Recurse into the right child with bounds (node.value, max) — everything right must stay above this node.
- The tree is valid only if every node passes its bound check.
Validate Worked Example
Input: Check tree: root 10, left 5, right 15 where 15's left child is 6
- Root 10: bounds (-inf, +inf) → valid
- Left 5: bounds (-inf, 10) → valid
- Right 15: bounds (10, +inf) → valid
- 15's left child 6: bounds (10, 15) → 6 is NOT > 10 → invalid!
Output: Tree is invalid: node 6 violates the BST property inherited from root 10
Press ▶ Run to watch it step by step.
def is_valid(root):
def check(n, lo, hi):
if not n:
return True
if not (lo < n.val < hi):
return False
return (check(n.left, lo, n.val) and
check(n.right, n.val, hi))
return check(root, float('-inf'), float('inf'))
# example: validateBehind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Validate Time & Space Complexity
When to Use Validate
- Sanity-checking a tree after bulk construction or deserialization
- Debugging BST insert/delete bugs
- Interview / teaching tool for the BST invariant
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Ready for the next step?
See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.