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.
| Call | Inherited interval | Check |
|---|---|---|
| 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
Reference drawing
Problem trace
Every node must satisfy all inherited ancestor bounds
Execution trace
Original coordinate inventory
- check -inf < 5 < inf
- (0, 3)
- input
- tree=[5,1,7,null,null,4,8]
- active check
- check -inf < 5 < inf
Original coordinate inventory
- check -inf < 1 < 5
- (0, 3)→(2, 1)
- active check
- check -inf < 5 < inf→check -inf < 1 < 5
- stack
- valid(5,-inf,inf)→valid(5,-inf,inf) -> valid(1,-inf,5)
Original coordinate inventory
- active check
- check -inf < 1 < 5→left subtree valid
- returns
- not shown→null=true, null=true, node 1=true
- stack
- valid(5,-inf,inf) -> valid(1,-inf,5)→not shown
Original coordinate inventory
- check 5 < 7 < inf
- (2, 1)→(2, 5)
- active check
- left subtree valid→check 5 < 7 < inf
- stack
- not shown→valid(5,-inf,inf) -> valid(7,5,inf)
Original coordinate inventory
- 5 < 4 < 7 is false
- (2, 5)→(4, 4)
- active check
- check 5 < 7 < inf→5 < 4 < 7 is false
- stack
- valid(5,-inf,inf) -> valid(7,5,inf)→valid(5,-inf,inf) -> valid(7,5,inf) -> valid(4,5,7)
Original coordinate inventory
- active check
- 5 < 4 < 7 is false→4 violates ancestor bound 5
- returns
- not shown→node 4=false -> node 7=false -> node 5=false
- result
- not shown→false
- 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.
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.