938. Range Sum of BST

https://leetcode.com/problems/range-sum-of-bst/

遍历一遍所有节点,将节点值在[L,R]间的计入。遍历时利用BST的性质将子树落在范围外的省去。

/*
 * @lc app=leetcode id=938 lang=cpp
 *
 * [938] Range Sum of BST
 */

// @lc code=start
/**
 * 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 {
public:
    int rangeSumBST(TreeNode* root, int L, int R) {
        stack<TreeNode*> s;
        s.push(root);
        int res = 0;
        while (!s.empty()) {
            const auto t = s.top(); s.pop();
            if (t == nullptr) continue;
            if (t->val > L) s.push(t->left);
            if (t->val < R) s.push(t->right);
            if (t->val >= L && t->val <= R) res += t->val;
        }
        return res;
    }
};
// @lc code=end

Last updated