题目:938. 二叉搜索树的范围和
难度: 简单
题目:
给定二叉搜索树的根结点 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 * 10^4] 内
- 1 <= Node.val <= 10^5
- 1 <= low <= high <= 10^5
- 所有 Node.val 互不相同
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/range-sum-of-bst/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解题思路
对于二叉树,简单的方法可以直接对其进行一次中序遍历,递归or迭代(非递归)都可以,每次根据val来选择是否增加。同时,考虑到这样会产生重复,所以需要剪枝操作,利用BST排序的性质,左子节点的值小于根节点,右子节点的值大于根节点。
解题代码
(1)朴素法
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
private:
int sum;
int l, h;
public:
int rangeSumBST(TreeNode* root, int low, int high) {
sum = 0;
l = low;
h = high;
inOrder(root);
return sum;
}
void InOrder(TreeNode* T)
{
if (!T) return;
InOrder(T->left);
visit(T);
InOrder(T->right);
}
void visit(TreeNode* T)
{
if(l <= T->val && T->val <= h)
{
sum += T->val;
}
}
void inOrder(TreeNode* T)
{
if (!T) return;
stack<TreeNode*> stk;
TreeNode* p = T;
while (!stk.empty() || p)
{
if (p)
{
stk.push(p);
p = p->left;
}
else
{
p = stk.top();
stk.pop();
visit(p);
p = p->right;
}
}
}
};
(2)剪枝
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int rangeSumBST(TreeNode* root, int low, int high) {
if (!root) return 0;
if (root->val > high) return rangeSumBST(root->left, low, high);
if (root->val < low) return rangeSumBST(root->right, low, high);
return root->val + rangeSumBST(root->left, low, high) + rangeSumBST(root->right, low, high);
}
};
解题感悟
解决二叉树中序遍历的问题,将遍历过程模拟一遍,就可轻松解题。
本文介绍了LeetCode中的938题——二叉搜索树的范围和,难度为简单。主要思路是对二叉搜索树进行中序遍历,通过剪枝优化避免重复计算。提供了解题代码,包括朴素法和剪枝法,并分享了解题感悟。

被折叠的 条评论
为什么被折叠?



