DSA Patterns (Multi-Lang)•Part 7: Binary Trees, BSTs & Traversals (53 - 64)
Validate Binary Search Tree.
In Simple Words:
Pass valid open interval (minVal, maxVal) recursively down the tree. Every node must satisfy minVal < node.val < maxVal. Left child inherits (minVal, node.val); right child inherits (node.val, maxVal).
- Time: $O(N)$ | Space: $O(H)$
Multi-Language SolutionsPython 3 • JavaScript • TypeScript • Java • C++
Switch tabs or choose Alldef isValidBST(root: TreeNode | None) -> bool:
def validate(node, low, high):
if not node: return True
if not (low < node.val < high):
return False
return validate(node.left, low, node.val) and validate(node.right, node.val, high)
return validate(root, float('-inf'), float('inf'))