LeetCode 题解工作台
二叉搜索树的范围和
给定二叉搜索树的根结点 root ,返回值位于范围 [low, high] 之间的所有结点的值的和。 示例 1: 输入: root = [10,5,15,3,7,null,18], low = 7, high = 15 输出: 32 示例 2: 输入: root = [10,5,15,3,7,13,…
4
题型
6
代码语言
3
相关题
当前训练重点
简单 · 二分·树·traversal
答案摘要
我们设计一个函数 ,表示求以 为根的子树中,值位于范围 $[low, high]$ 之间的所有结点的值的和。那么答案就是 。 函数 的执行逻辑如下:
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 二分·树·traversal 题型思路
题目描述
给定二叉搜索树的根结点 root,返回值位于范围 [low, high] 之间的所有结点的值的和。
示例 1:
输入:root = [10,5,15,3,7,null,18], low = 7, high = 15 输出:32
示例 2:
输入:root = [10,5,15,3,7,13,18,1,null,6], low = 6, high = 10 输出:23
提示:
- 树中节点数目在范围
[1, 2 * 104]内 1 <= Node.val <= 1051 <= low <= high <= 105- 所有
Node.val互不相同
解题思路
方法一:DFS
我们设计一个函数 ,表示求以 为根的子树中,值位于范围 之间的所有结点的值的和。那么答案就是 。
函数 的执行逻辑如下:
- 如果 为空,返回 。
- 如果 的值 在范围 之间,那么函数 的初始答案就是 ,否则为 。
- 如果 ,说明 的左子树中可能有值在范围 之间的结点,所以我们需要递归调用 ,并将结果加到答案上。
- 如果 ,说明 的右子树中可能有值在范围 之间的结点,所以我们需要递归调用 ,并将结果加到答案上。
- 最后返回答案。
时间复杂度 ,空间复杂度 。其中 是二叉搜索树的结点个数。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int:
def dfs(root: Optional[TreeNode]) -> int:
if root is None:
return 0
x = root.val
ans = x if low <= x <= high else 0
if x > low:
ans += dfs(root.left)
if x < high:
ans += dfs(root.right)
return ans
return dfs(root)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Can the candidate optimize the traversal to reduce redundant checks?
- question_mark
Does the candidate demonstrate understanding of tree pruning based on BST properties?
- question_mark
Can the candidate implement both recursive and iterative solutions efficiently?
常见陷阱
外企场景- error
Ignoring the BST properties and performing unnecessary traversal of both subtrees even when pruning is possible.
- error
Misunderstanding the range inclusion, potentially excluding or including the bounds incorrectly.
- error
Failing to handle deep recursion or stack overflow issues in large trees when using recursion.
进阶变体
外企场景- arrow_right_alt
Consider solving the problem using a breadth-first search (BFS) approach.
- arrow_right_alt
What if the tree is not a BST? How would you adjust the approach?
- arrow_right_alt
How does the solution change if the range is dynamically updated during traversal?