空闲做每日一题
给定二叉搜索树的根结点 root,返回值位于范围 [low, high] 之间的所有结点的值的和
发现和之前一样,也是递归更好用一点。
c++实现
#include<iostream>
#include<vector>
using namespace std;
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:
void myRecurFunc(TreeNode* root, int low, int high, std::vector<int>& nums)
{
if (root == nullptr) return;
if (root->val >= low && root->val <= high)
{
nums.push_back(root->val);
myRecurFunc(root->left, low, high, nums);
myRecurFunc(root->right, low, high, nums);
}
else if (root->val < low)
{
myRecurFunc(root->right, low, high, nums);
}
else if (root->val > high)
{
myRecurFunc(root->left, low, high, nums);
}
}
int rangeSumBST(TreeNode* root, int low, int high) {
std::vector<int> nums;
myRecurFunc(root, low, high, nums);
if (nums.size() == 0) return 0;
int sum = 0;
for (const auto& item : nums)
{
sum += item;
}
return sum;
}
};