LeetCode 938. 二叉搜索树的范围和
原题链接
简单
作者:
回归线
,
2021-04-27 11:04:50
,
所有人可见
,
阅读 292
/**
* 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;
}
const int v = root->val;
if (v < low) {
return rangeSumBST(root->right, low, high);
}
if (v > high) {
return rangeSumBST(root->left, low, high);
}
return v + rangeSumBST(root->left, low, high) + rangeSumBST(root->right, low, high);
}
};