CodeArchon

mediumTreesAmazonMicrosoftFacebook

Sorted Catalog Verifier

A librarian audits a hierarchical shelf catalog to confirm it satisfies the BST ordering invariant across every ancestor-descendant pair.

Given the root of a binary tree, determine if it is a valid binary search tree (BST). Left subtree contains only values strictly less than the node; right subtree only values strictly greater.

Choose approach

5
-∞<x<+∞
curr
1
4
3
6
1/5
Narrationstep 1 of 5

Check Node 5: must satisfy -∞ < val < +∞.

1def isValidBST(root: Optional[TreeNode]) -> bool:
2 def validate(node, lo, hi):
3 if not node:
4 return True
5 if node.val <= lo or node.val >= hi:
6 return False
7 return validate(node.left, lo, node.val) and validate(node.right, node.val, hi)
8 return validate(root, float('-inf'), float('inf'))
Variables
node=5
lo=-∞
hi=+∞

How to think about it

  1. Root receives bounds (-∞, +∞).
  2. Left child inherits (lo, parent.val); right child inherits (parent.val, hi).
  3. Any violation anywhere kills validity.

Edge cases to catch in interview

  • Empty tree -> valid.
  • Equal values anywhere -> invalid (strict inequality).

Examples

Example 1true
{"arr":[2,1,3]}
Example 2false
{"arr":[5,1,4,null,null,3,6]}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed