题目:【https://leetcode.cn/problems/range-sum-of-bst/description/】
给定二叉搜索树的根结点 root
,返回值位于范围 [low, high]
之间的所有结点的值的和。
示例:
输入:root = [10,5,15,3,7,null,18], low = 7, high = 15
输出:32
代码:(二叉树的深度有限遍历和递归)
/**
* 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 == nullptr) {
return 0;
}
if (root->val > high) {
// 在左子树中
return rangeSumBST(root->left, low, high);
} else if (root->val < low) {
// 在右子树中
return rangeSumBST(root->right, low, high);
} else {
// 左右子树中均有在范围中的
return root->val + rangeSumBST(root->left, low, high) + rangeSumBST(root->right, low, high);
}
}
};