题目描述
给定二叉搜索树的根结点 root,返回值位于范围 [low, high] 之间的所有结点的值的和。
C++
/**
* 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) {}
* };
*/
/*
递归停止条件:节点为空
返回什么: 范围内节点值和
本级递归干什么:比较是否在边界区间,当前节点和边界区间的关系只有三种:val在区间内;val小于左区间;val>右区间;
*/
class Solution {
public:
int rangeSumBST(TreeNode* root, int low, int high) {
if(!root) return 0;
if(root->val<low) return rangeSumBST(root->right,low,high);
if(root->val>high) return rangeSumBST(root->left,low,high);
return root->val+rangeSumBST(root->left,low,high)+rangeSumBST(root->right,low,high);
}
};