对二叉树进行遍历,再对比值
/**
-
Definition for a binary tree node.
-
struct TreeNode {
-
int val;
-
TreeNode *left;
-
TreeNode *right;
-
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
-
};
/
class Solution {
private:
int count=0;
public:
int rangeSumBST(TreeNode root, int L, int R)
{
if(root==NULL)return 0;
if(root->val>=L&&root->val<=R)
{
count+=root->val;
rangeSumBST(root->left,L,R);
rangeSumBST(root->right,L,R);} else if(root->val<L)rangeSumBST(root->right,L,R); else if(root->val>R)rangeSumBST(root->left,L,R); return count;
}
};
代码可以简化成这样
int rangeSumBST(TreeNode* root, int L, int R)
{
if(root==NULL)return 0;
if(root->val<L)return rangeSumBST(root->right,L,R);
else if(root->val>R) return rangeSumBST(root->left,L,R);
else return root->val+ rangeSumBST(root->left,L,R)+ rangeSumBST(root->right,L,R);
}