QuestionsDSA

Validate Binary Search Tree

DFS (Depth-First)MediumDSA

Determine whether a binary tree is a valid BST: every node's left subtree holds only smaller values, its right subtree only larger, and both subtrees are themselves valid BSTs.

What it tests

Understanding that BST validity is a global range constraint, not just a local parent-child check.

Approach & answer

The classic wrong answer only compares each node to its immediate children — that passes trees that aren't BSTs, because a node deep in the left subtree can still exceed the root. Validity is a *range* property: carry a (low, high) open interval down the recursion. The root is unbounded (-∞, +∞); going left tightens the upper bound to the parent's value, going right tightens the lower bound. A node is valid iff `low < node.val < high` and both children validate against their narrowed ranges. Use strict comparisons if duplicates are disallowed. An equivalent solution: an in-order traversal of a BST yields strictly increasing values, so walk in-order tracking the previous value and fail if it ever doesn't increase — that's often the cleaner code. Either way it's DFS carrying state down (the range) versus DFS reading state across (the in-order predecessor).

Use this technique when

Tree property that depends on ancestors, not just parent → DFS carrying a (low, high) range down each branch.

Complexity

Time O(n) · Space O(h) recursion

References

js