NeetCode #408LC-333MediumTreesNC Algo100
← Back to All Problems#408 · #333 · Largest BST Subtree(最大 BST 子树)
📌 Problem Statement & Constraints
Given the root of a binary tree, return the size of the largest subtree that is also a binary search tree. Constraints: the number of nodes is in
[0, 10^4], -10^4 <= Node.val <= 10^4.💡 Core Algorithmic Approaches
- A post-order DFS returns, for each subtree,
(size, min, max)if it is a BST, or a sentinel if it is not. - A subtree is a BST when both children are BSTs, the left maximum is less than the node's value, and the right minimum is greater.
- Track the maximum BST size found.
- Returning
Nonefor non-BST subtrees short-circuits the propagation cleanly.
💻 Benchmark Python3 Implementation
class Solution:
def largestBSTSubtree(self, root: Optional[TreeNode]) -> int:
self.best = 0
def dfs(node: Optional[TreeNode]):
"""Return (size, min, max) if the subtree is a BST, else None."""
if not node:
return (0, float("inf"), float("-inf")) # neutral identity
l = dfs(node.left)
r = dfs(node.right)
if l is None or r is None:
return None # a child subtree is not a BST
ls, lmin, lmax = l
rs, rmin, rmax = r
if lmax >= node.val or rmin <= node.val:
return None # ordering violated here
size = ls + rs + 1
self.best = max(self.best, size)
return (size, min(lmin, node.val), max(rmax, node.val))
dfs(root)
return self.best⚡ Complexity Deep Dive
⏱️ Time Complexity
O(n): each node is visited once.
💾 Space Complexity
O(h) for the recursion stack.
⚠️ Interview Pitfalls & Follow-ups
- Using an in-order traversal and tracking the longest increasing run: a longest-increasing run is necessary but not sufficient for a BST (a right subtree can violate an ancestor's bound).
- Returning
Nonebut still using the child's size: the parent must propagate the failure. - Initialising the empty subtree with
(0, 0, 0): that would corrupt the min/max comparisons;(0, +inf, -inf)is the correct identity. - Forgetting to update
self.bestfor leaves: the update happens for every valid subtree, including single nodes.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🧩 Related Trees Problems
中文速览与面试要点
最大 BST 子树
给定一个二叉树,找到其中 最大的二叉搜索子树 ,其中最大指的是子树 节点数最多 的二叉树。注意:子树必须包含其所有后代。约束:树中节点数范围是 [1, 10^4];0 ≤ Node.val ≤ 10^4。
核心要点
- 后序遍历返回四元组(标准解) :递归函数返回 (是否为 BST, 子树最小值, 子树最大值, 子树节点数) 。
- 判定条件 :左子树是 BST、右子树是 BST、 左子树最大值 < node.val < 右子树最小值 ,三者同时成立时当前子树才是 BST。
- 更新最优 :当前子树是 BST 时,用它的节点数更新全局最大值。
- 为什么必须返回 min/max :父节点需要「左子树的最大值」与「右子树的最小值」才能判断 BST 性质。
- 空节点处理 :返回 (True, +∞, −∞, 0) ,这样任何真实节点都能满足与空子树的比较条件。
常见陷阱
- 空节点返回 (True, 0, 0, 0) :会让 l_max < node.val 的判断失效(当节点值为负数时)。必须用 ±∞。
- 只判断 左.最大值 < node.val 而不判断 node.val < 右.最小值 :会漏掉右子树的约束。
- 忘记在 return (False, ...) 时把 min/max 置为无效值 :父节点会用到它们,必须确保父节点在 l_ok / r_ok 为 False 时不会误用。本解中父节点会先检查 l_ok and r_ok ,因此安全。
- best 初值设为 0 :若树为空返回 0,正确;节点值非负,单节点子树必然计入。
- 用「枚举所有子树 + 逐一验证」 :O(n²) 会超时。
参考实现
class Solution:
def largestBSTSubtree(self, root: 'TreeNode') -> int:
best = 0
def dfs(node):
"""返回 (是否 BST, 最小值, 最大值, 节点数)。"""
nonlocal best
if not node:
return (True, float('inf'), float('-inf'), 0)
l_ok, l_min, l_max, l_cnt = dfs(node.left)
r_ok, r_min, r_max, r_cnt = dfs(node.right)
# 当前子树是 BST 的条件
if l_ok and r_ok and l_max < node.val < r_min:
cnt = l_cnt + r_cnt + 1
if cnt > best:
best = cnt
# 注意:min/max 需结合自身值
return (True, min(l_min, node.val), max(r_max, node.val), cnt)
# 不是 BST:返回 False,min/max/cnt 已无意义
return (False, 0, 0, 0)
dfs(root)
return best