英文原文
Given the root
node of a binary search tree and two integers low
and high
, return the sum of values of all nodes with a value in the inclusive range [low, high]
.
Example 1:

Input: root = [10,5,15,3,7,null,18], low = 7, high = 15 Output: 32 Explanation: Nodes 7, 10, and 15 are in the range [7, 15]. 7 + 10 + 15 = 32.
Example 2:

Input: root = [10,5,15,3,7,13,18,1,null,6], low = 6, high = 10 Output: 23 Explanation: Nodes 6, 7, and 10 are in the range [6, 10]. 6 + 7 + 10 = 23.
Constraints:
- The number of nodes in the tree is in the range
[1, 2 * 104]
. 1 <= Node.val <= 105
1 <= low <= high <= 105
- All
Node.val
are unique.
中文题目
给定二叉搜索树的根结点 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 <= 105
1 <= low <= high <= 105
- 所有
Node.val
互不相同
通过代码
高赞题解
解题思路
- 标签:深度优先遍历
- 题意:这个题字面含义很难理解,本意就是求出所有
X >= L
且X <= R
的值的和 - 递归终止条件:
- 当前节点为 null 时返回 0
- 当前节点
X < L
时则返回右子树之和 - 当前节点
X > R
时则返回左子树之和 - 当前节点
X >= L
且X <= R
时则返回:当前节点值 + 左子树之和 + 右子树之和
- 注意点:通过判断X的大小能够避免遍历全部树的节点,比如下方的动图中,3 这个值就没有必要遍历
代码
[]/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public int rangeSumBST(TreeNode root, int L, int R) { if (root == null) { return 0; } if (root.val < L) { return rangeSumBST(root.right, L, R); } if (root.val > R) { return rangeSumBST(root.left, L, R); } return root.val + rangeSumBST(root.left, L, R) + rangeSumBST(root.right, L, R); } }
画解
<,
,
,
,
,
,
,
,
,
,
>
想看大鹏画解更多高频面试题,欢迎阅读大鹏的 LeetBook:《画解剑指 Offer 》,O(∩_∩)O
统计信息
通过次数 | 提交次数 | AC比率 |
---|---|---|
99767 | 121749 | 81.9% |
提交历史
提交时间 | 提交结果 | 执行时间 | 内存消耗 | 语言 |
---|