NeetCode #395LC-938EasyTrees
← Back to All Problems#395 · #938 · Range Sum of BST(二叉搜索树的范围和)
📌 Problem Statement & Constraints
Given the root of a binary search tree and two integers
low and high, return the sum of all values in the inclusive range [low, high]. Constraints: the number of nodes is in [1, 2 * 10^4], 1 <= Node.val <= 10^5, 1 <= low <= high <= 10^5.💡 Core Algorithmic Approaches
- Exploit the BST ordering to prune the traversal.
- If the node's value is below
low, the entire left subtree is also belowlow, so only recurse right. - If the value is above
high, only recurse left. - Otherwise include the value and recurse into both subtrees.
💻 Benchmark Python3 Implementation
class Solution:
def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int:
if not root:
return 0
if root.val < low:
return self.rangeSumBST(root.right, low, high) # left subtree is all too small
if root.val > high:
return self.rangeSumBST(root.left, low, high) # right subtree is all too large
return (root.val
+ self.rangeSumBST(root.left, low, high)
+ self.rangeSumBST(root.right, low, high))⚡ Complexity Deep Dive
⏱️ Time Complexity
O(n) worst case, but typically much less because whole subtrees are pruned.
💾 Space Complexity
O(h) for the recursion stack.
⚠️ Interview Pitfalls & Follow-ups
- Traversing the whole tree unconditionally: correct but misses the BST pruning that is the point of the problem.
- Pruning with
<=instead of<: the bounds are inclusive, so a node equal toloworhighmust be included. - Recursing into both subtrees when one is prunable: that defeats the optimisation.
- Assuming the tree is balanced: the worst case is still O(n).
⚡
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
中文速览与面试要点
二叉搜索树的范围和
给定二叉搜索树的根结点 root,返回值位于范围 [low, high] 之间的所有结点的值的和。约束:树中节点数目在范围 [1, 2 × 10^4] 内;1 ≤ Node.val ≤ 10^5;1 ≤ low ≤ high ≤ 10^5;所有 Node.val 互不相同 。
核心要点
- 利用 BST 有序性剪枝(标准解) :若 root.val < low ,则左子树全部小于 low,只需递归右子树;若 root.val > high ,则右子树全部大于 high,只需递归左子树。
- 为什么剪枝有效 :BST 的中序遍历升序,因此当前节点与 low/high 的大小关系能确定整棵子树的范围。
- 复杂度 :最坏 O(n),但实际因剪枝通常远小于 n。
- 对比遍历全部节点 :不剪枝也是 O(n),但剪枝能显著减少访问量。
常见陷阱
- 不剪枝直接遍历所有节点 :虽然正确,但未利用 BST 的有序性。
- 剪枝时递归错子树 : root.val < low 时应递归 右 子树(左子树全部小于 low)。
- 边界用 <= 而非 < :题目要求闭区间 [low, high],因此 root.val == low 或 == high 都应计入。
参考实现
class Solution:
def rangeSumBST(self, root: 'TreeNode', low: int, high: int) -> int:
if not root:
return 0
if root.val < low: # 整棵左子树都小于 low
return self.rangeSumBST(root.right, low, high)
if root.val > high: # 整棵右子树都大于 high
return self.rangeSumBST(root.left, low, high)
# 当前节点在范围内
return (root.val
+ self.rangeSumBST(root.left, low, high)
+ self.rangeSumBST(root.right, low, high))