A node is valid only if its value is strictly between a min_value and a max_value. When moving left, we update the max_value. When moving right, we update the min_value.
- Define a helper function
validate(node, min_val, max_val). - If
nodeis None, return True. - If
node.val<=min_valornode.val>=max_val, return False. - Check subtrees:
validate(node.left, min_val, node.val)validate(node.right, node.val, max_val)
- Return the logical AND of these checks.
- Time Complexity: O(N).
- Space Complexity: O(H).
def is_valid_bst(root):
def validate(node, low=-float('inf'), high=float('inf')):
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)