LeetCode 938. 二叉搜索树的范围和

给定二叉搜索树的根结点 root,返回值位于范围 [low, high] 之间的所有结点的值的和。

直接找即可:

/**
 * 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:
    void findTarget(TreeNode *root, int low, int high, int &sum) {
        if (nullptr == root) {
            return;
        }

        if (root->val < low) {
            findTarget(root->right, low, high, sum);
        } else if (root->val > high) {
            findTarget(root->left, low, high, sum);
        } else {
            sum += root->val;
            findTarget(root->right, low, high, sum);
            findTarget(root->left, low, high, sum);
        }
    }

    int rangeSumBST(TreeNode* root, int low, int high) {
        int ret = 0;

        findTarget(root, low, high, ret);

        return ret;
    }
};
上一篇:Leetcode-938 二叉搜索树的范围和


下一篇:3441:4 Values whose Sum is 0(二分查找)