240
笔下虽有千言,胸中实无一策

30 Day Challenge Day 20 | Leetcode 938. Range Sum of BST

题解

Easy

Recursion

class Solution {
public:
    int rangeSumBST(TreeNode* root, int L, int R) {
        if(!root) return 0;
        if(root->val < L) return rangeSumBST(root->right, L, R);
        if(root->val > R) return rangeSumBST(root->left, L, R);
        
        return root->val + rangeSumBST(root->left, L, root->val) + rangeSumBST(root->right, root->val, R);
    }
};

DFS

class Solution {
public:
    int rangeSumBST(TreeNode* root, int L, int R) {
        int sum = 0;
        dfs(root, L, R, sum);
        return sum;
    }
    
    void dfs(TreeNode* node, int L, int R, int& sum) {
        if(!node) return;
        
        if(node->val >= L && node->val <= R) {
            sum += node->val;
            dfs(node->right, L, R, sum);
            dfs(node->left, L, R, sum);
        }
        
        if(node->val < L) dfs(node->right, L, R, sum);
        
        if(node->val > R) dfs(node->left, L, R, sum);
    }
};
posted @ 2020-10-08 08:45  CasperWin  阅读(98)  评论(0编辑  收藏  举报