1. 题目

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

例子1:
image.png

  1. 输入:root = [10,5,15,3,7,null,18], low = 7, high = 15
  2. 输出:32

例子2:
image.png

输入:root = [10,5,15,3,7,13,18,1,null,6], low = 6, high = 10
输出:23

提示:

  • 树中节点数目在范围 [1, 2 * 104]
  • 1 <= Node.val <= 105
  • 1 <= low <= high <= 105
  • 所有Node.val 互不相同

解1:

  • 需要遍历所有元素 ```cpp /**
    • 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 { private: int result = 0;

public: int rangeSumBST(TreeNode* root, int low, int high) { if (root == nullptr) return 0;

    if (root->val >= low && root->val <= high) {
        result += root->val;
    }

    rangeSumBST(root->left, low, high);
    rangeSumBST(root->right, low, high);

    return result;
}

};


<a name="pF4ev"></a>
# 解二(在解一的基础上优化):

- 因为这是二叉搜索树,是**有序的**,所以只要达到了范围,就不需要继续往下搜索,就调整搜索范围
- 通过判断`node->val`的大小能够**避免遍历全部树的节点**

```cpp
/**
 * 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 {
private:
    int result = 0;

public:
    int rangeSumBST(TreeNode* root, int low, int high) {
        if (root == nullptr)
            return 0;

        if (root->val >= low && root->val <= high) {
            result += root->val;
        }

        if (root->val >= low) {
            rangeSumBST(root->left, low, high);
        }

        if (root->val <= high) {
            rangeSumBST(root->right, low, high);
        }

        return result;
    }
};