Problem 461098 · medium · Level 04 Non-Linear Data Structures

Audit a Search Tree

BST · recursion · in-order traversal

A binary search tree (BST) keeps an order rule at every node: everything in the node's left subtree is strictly smaller than the node's value, and everything in its right subtree is strictly larger. Searching is fast only because the rule holds everywhere; a single misplaced value makes searches quietly miss it.

You are auditing a tree that someone else built. Write is_valid_bst(root) that returns True when the order rule holds at every node and False otherwise. Equal values break the rule (duplicates are not allowed), and an empty tree passes.

Examples

  7
 / \
3   10

Input:  root = [7, 3, 10]
Output: True
    8
   / \
  3   6
     / \
    5   9

Input:  root = [8, 3, 6, None, None, 5, 9]
Output: False
Explanation: The root's right child is 6, but 6 < 8.
      20
     /  \
   10    30
   / \
  5   25

Input:  root = [20, 10, 30, 5, 25]
Output: False
Explanation: Node 25 is in the left subtree of 20, so it must be smaller than 20.

Constraints

  • 0 <= number of nodes <= 1000
  • -10**9 <= node.val <= 10**9

Goals

  • State the BST invariant precisely (it applies to whole subtrees, not just direct children)
  • Pass allowed bounds (low, high) down a recursion
  • Alternatively, use the fact that an in-order traversal of a BST is strictly increasing
Starting Python…