[每日一题]leetcode 938. 二叉搜索树的范围和

/**
 * 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;
        int sum = 0;
        sum = rangeSumBST(root->left, low, high);
        sum += rangeSumBST(root->right, low, high);
        if(root->val >= low && root->val <= high) sum += root->val;
        return sum;
    }
};

 

posted @ 2021-04-27 17:28  WTSRUVF  阅读(30)  评论(0编辑  收藏  举报