Skip to content
mlmentorship

Validate Binary Search Tree

Carry every ancestor's ordering constraint as an interval, reject a hidden descendant violation, and change traversal or duplicate placement deliberately.

Published · 15 min read ·Core ·Mixed

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

ML breadth · closed-book attempt

Validate Binary Search Tree

Explain the mechanism, why it works, when it fails, and one alternative.

Problem

Input. The root of a finite integer-valued binary tree without cycles or shared children. Output. Return True exactly when the tree is a valid strict binary search tree. Rules. Every value in a node's left subtree must be smaller than that node's value. Every value in its right subtree must be larger, and both rules apply recursively. Duplicates are forbidden. Preserve the tree; an empty tree returns True. Example. Root 2 with children 1 and 3 returns True. Root 5 with right child 7 and 7.left = 4 returns False: 4 violates the ancestor's right-subtree requirement.

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

30-second answer map

Validate each node against the complete interval inherited from every ancestor.

Problem trace

Every node must satisfy all inherited ancestor bounds

Input and goalCheck whether every node follows all BST ordering rules.
Call valid(5, -inf, inf)Root 5 passes its open interval (-inf, inf). Validate left before right.
-inf < 5 < inf51748
Original coordinate inventory
5check -inf < 5 < inf/\17/\48
inputtree=[5,1,7,null,null,4,8]activeCheckcheck -inf < 5 < infstackvalid(5,-inf,inf)
check -inf < 5 < inf
(0, 3)
input
tree=[5,1,7,null,null,4,8]
active check
check -inf < 5 < inf

Recognize it
BST validity applies against every ancestor, so a local parent-child comparison is insufficient and each recursive call must carry the legal value interval.
Keep true
At valid(node, low, high), every ancestor constraint is summarized by low < node.val < high; the left call tightens high and the right call tightens low.
Reuse it
When a recursive descendant must satisfy all ancestor decisions, summarize those decisions as constraints in the call state rather than rechecking only the parent.
Root 5 passes its open interval (-inf, inf). Validate left before right. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why is 4 invalid as 7's left child even though 4 is less than 7?
Full interview answer 15 min read

Determine whether a binary tree satisfies strict binary-search ordering across every complete subtree.

Problem

Input. The root of a finite integer-valued binary tree without cycles or shared children.

Output. Return True exactly when the tree is a valid strict binary search tree.

Rules. Every value in a node’s left subtree must be smaller than that node’s value. Every value in its right subtree must be larger, and both rules apply recursively. Duplicates are forbidden. Preserve the tree; an empty tree returns True.

Example. Root 2 with children 1 and 3 returns True. Root 5 with right child 7 and 7.left = 4 returns False: 4 violates the ancestor’s right-subtree requirement.

Picture

Node 4 is smaller than parent 7. But it lies in root 5’s right subtree, where every value must exceed five.

CallInherited intervalCheck
Root 5(-inf, inf)Pass
Left child 1(-inf, 5)Pass
Right child 7(5, inf)Pass
Left child 4 under 7(5, 7)Fail

Problem trace

Separate descendant violation: satisfy every inherited ancestor bound

Worked example: a descendant must satisfy every inherited ancestor boundNode 12 fits above parent 5 but violates ancestor 10. Every descendant in that ancestor's left subtree must remain below 10.The descendant inherits everyancestor boundary10512Everything in ancestor ten's leftsubtree must remain below ten.51012Strictly between five and ten; twelvelies outside.
Read it this way: Node 12 fits above parent 5 but violates ancestor 10. Every descendant in that ancestor's left subtree must remain below 10. Why does satisfying parent five still fail the upper bound inherited from ancestor ten?
Reference drawing

Problem trace

Every node must satisfy all inherited ancestor bounds

Worked example: a descendant must satisfy every inherited ancestor boundNode 12 fits above parent 5 but violates ancestor 10. Every descendant in that ancestor's left subtree must remain below 10.The descendant inherits everyancestor boundary10512Everything in ancestor ten's leftsubtree must remain below ten.51012Strictly between five and ten; twelvelies outside.
Execution trace
Input and goalCheck whether every node follows all BST ordering rules.
Call valid(5, -inf, inf)Root 5 passes its open interval (-inf, inf). Validate left before right.
-inf < 5 < inf51748
Original coordinate inventory
5check -inf < 5 < inf/\17/\48
inputtree=[5,1,7,null,null,4,8]activeCheckcheck -inf < 5 < infstackvalid(5,-inf,inf)
check -inf < 5 < inf
(0, 3)
input
tree=[5,1,7,null,null,4,8]
active check
check -inf < 5 < inf

Recognize it
BST validity applies against every ancestor, so a local parent-child comparison is insufficient and each recursive call must carry the legal value interval.
Keep true
At valid(node, low, high), every ancestor constraint is summarized by low < node.val < high; the left call tightens high and the right call tightens low.
Reuse it
When a recursive descendant must satisfy all ancestor decisions, summarize those decisions as constraints in the call state rather than rechecking only the parent.
Root 5 passes its open interval (-inf, inf). Validate left before right. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why is 4 invalid as 7's left child even though 4 is less than 7?
Read it this way: Node 12 fits above parent 5 but violates ancestor 10. Every descendant in that ancestor's left subtree must remain below 10. Why does satisfying parent five still fail the upper bound inherited from ancestor ten?

Code

Use this node type for a local run.

from dataclasses import dataclass


@dataclass
class TreeNode:
   val: int
   left: "TreeNode | None" = None
   right: "TreeNode | None" = None
def is_valid_bst(root: TreeNode | None) -> bool:
   def valid(node: TreeNode | None, low: float, high: float) -> bool:
      if node is None:
         return True
      if not low < node.val < high:
         return False
      return valid(node.left, low, node.val) and valid(node.right, node.val, high)

   return valid(root, float("-inf"), float("inf"))

Keep All Ancestor Constraints

At valid(node, low, high), the open interval summarizes every ancestor’s restrictions.

Moving left replaces the upper bound with node.val. Moving right replaces the lower bound. The other inherited bound remains.

An empty subtree adds no violation, so it returns True. A failed comparison returns False immediately.

The conjunction checks left before right. In the example, rejection of 4 skips node 8 and propagates to the root.

Strict comparisons reject equality with any bound, not merely an equal parent.

Worst-case time is and call-stack space for tree height . No links or values change.

Deep trees can exceed Python’s recursion limit. The numeric infinity sentinels do not support arbitrary comparable types such as strings.

The platform supplies TreeNode with val, left, and right; this snippet assumes that definition.

Recall: Why does the left call keep its inherited lower bound? A left turn does not cancel earlier right-subtree restrictions.

Validate Strict Inorder Emissions

Choose this when: You want an explicit stack or comparable values that do not mix with numeric infinities.

Inorder visits left, node, right. A strict BST emits a strictly increasing sequence; every violation must break that order.

def valid_bst_inorder(root):
   stack, node = [], root
   previous, has_previous = None, False
   while stack or node is not None:
      while node is not None:
         stack.append(node)
         node = node.left
      node = stack.pop()
      if has_previous and not previous < node.val:
         return False
      previous, has_previous = node.val, True
      node = node.right
   return True

The flag separates “nothing emitted” from a previous value. Values must share a consistent strict total order.

The pictured tree emits 1,5,4 before rejection. The decrease from five to four exposes the ancestor violation.

This takes worst-case time and explicit stack space, without recursive calls.

Permit Duplicates Only on the Right

Choose this when: The tree contract explicitly assigns equal values to right subtrees.

Keep the lower bound inclusive and the upper bound exclusive. An inherited upper restriction must still reject equality.

def valid_bst_duplicates_right(root):
   stack = [(root, None, None)]
   while stack:
      node, low, high = stack.pop()
      if node is None:
         continue
      if low is not None and node.val < low:
         return False
      if high is not None and not node.val < high:
         return False
      stack.append((node.right, node.val, high))
      stack.append((node.left, low, node.val))
   return True

Here None denotes an absent bound, not a permitted key.

A root two with right child two passes; the same equal child on the left fails.

Both trees have nondecreasing inorder values. That weaker emission test cannot enforce where duplicates occur.

Worst-case time is and explicit stack space . The input remains unchanged.