⚡Flashcard Drill➔
NeetCode #442LC-98MediumTreesBlind 75NC 150NC 250
← Back to All Problems

#442 · #98 · Validate Binary Search Tree(验证二叉搜索树)

📌 Problem Statement & Constraints

Given the root of a binary tree, determine whether it is a valid binary search tree: every node's value must be strictly greater than all values in its left subtree and strictly less than all values in its right subtree. Constraints: the number of nodes is in [1, 10^4], -2^31 <= Node.val <= 2^31 - 1.

💡 Core Algorithmic Approaches

  1. Checking only that each node's value lies between its immediate children is insufficient -- a violation can occur several levels deep.
  2. Carry the allowed open interval (lo, hi) down the recursion.
  3. Going left tightens hi to the current value; going right tightens lo.
  4. A node is valid when lo < node.val < hi. The initial interval is (-infinity, +infinity).

💻 Benchmark Python3 Implementation

class Solution:
    def isValidBST(self, root: Optional[TreeNode]) -> bool:
        def check(node: Optional[TreeNode], lo: float, hi: float) -> bool:
            if not node:
                return True
            if not (lo < node.val < hi):   # outside the allowed open interval
                return False
            return (check(node.left, lo, node.val)
                    and check(node.right, node.val, hi))

        return check(root, float("-inf"), float("inf"))


# In-order variant: the traversal must be strictly increasing
class Solution2:
    def isValidBST(self, root: Optional[TreeNode]) -> bool:
        prev = float("-inf")

        def inorder(node: Optional[TreeNode]) -> bool:
            nonlocal prev
            if not node:
                return True
            if not inorder(node.left):
                return False
            if node.val <= prev:           # not strictly increasing
                return False
            prev = node.val
            return inorder(node.right)

        return inorder(root)

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n): every node is visited once.
💾 Space Complexity
O(h) for the recursion stack.

⚠️ Interview Pitfalls & Follow-ups

  • Only comparing a node with its immediate children: [10, 5, 15, null, null, 6, 20] passes that test but is invalid, because 6 is in the right subtree of 10. The interval approach catches it.
  • Using closed intervals lo <= node.val <= hi: duplicate values are not allowed, so the bounds must be strict.
  • Initialising the interval with float('-inf')/float('inf'): correct, and safe even for 32-bit extreme values. Using -231 and 231 - 1 as bounds would break for a node with exactly those values.
  • Comparing with the previous node in a pre-order traversal: only the in-order traversal gives the sorted order.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Trees Problems

中文速览与面试要点

验证二叉搜索树

给你一个二叉树的根节点 root,判断其是否是一个有效的二叉搜索树。 有效 二叉搜索树定义如下:节点的左子树只包含 小于 当前节点的数;节点的右子树只包含 大于 当前节点的数;所有左子树和右子树自身必须也是二叉搜索树。约束:树中节点数目范围在 [1, 10^4] 内;-2^31 ≤ Node.val ≤ 2^31 − 1。

核心要点

  • 递归 + 上下界(标准解) :递归时传递每个节点允许的取值区间 (lo, hi) 。左子树的区间是 (lo, node.val) ,右子树是 (node.val, hi) 。
  • 为什么不能只比较父子节点 :BST 要求「整棵左子树都小于当前节点」,只比较直接子节点会漏掉深层违规。例如 [5,1,4,null,null,3,6] 中 4 的左子节点 3 小于 4,但 3 出现在 5 的右子树中,违反 BST 定义。
  • 中序遍历方案 :BST 的中序遍历必然是 严格递增 的,因此可以边遍历边检查前一个值是否小于当前值。
  • 初始区间用 ±∞ :Node.val 可达 ±2^31,用 Python 的 float("inf") 安全;C++/Java 中应使用 long long 。

常见陷阱

  • 只比较父子节点 :会漏掉「孙节点违反区间约束」的情况。必须传递上下界。
  • 上下界用开区间写成闭区间 :BST 要求 严格 小于/大于,必须用 lo &lt; val &lt; hi 。
  • 初始区间用 [-2^31, 2^31-1] :Node.val 恰好可以取到边界值,会误判。应用 ±∞。
  • 中序遍历时用 &lt; 而非 &lt;= 检查 :必须检查严格递增( &lt;= 即为违规)。

参考实现

class Solution:
    def isValidBST(self, root: 'TreeNode') -> bool:
        def check(node, lo, hi) -> bool:
            if not node:
                return True
            if not (lo < node.val < hi):        # 必须严格在区间内
                return False
            return (check(node.left, lo, node.val)
                    and check(node.right, node.val, hi))

        return check(root, float('-inf'), float('inf'))

# 中序遍历方案(迭代,空间 O(h))
# def isValidBST(self, root):
#     stack, cur = [], root
#     prev = float('-inf')
#     while cur or stack:
#         while cur:
#             stack.append(cur); cur = cur.left
#         cur = stack.pop()
#         if cur.val <= prev: return False
#         prev = cur.val
#         cur = cur.right
#     return True