--- tags: leetcode --- # [938. Range Sum of BST](https://leetcode.com/problems/range-sum-of-bst/) --- # My Solution ## The Key Idea for Solving This Coding Question ## C++ Code 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 { public: int rangeSumBST(TreeNode *root, int low, int high) { int answer = 0; dfs(root, low, high, answer); return answer; } private: void dfs(TreeNode *root, int low, int high, int &answer) { if (root == nullptr) { return; } if (root->val < low) { dfs(root->right, low, high, answer); return; } if (high < root->val) { dfs(root->left, low, high, answer); return; } answer += root->val; dfs(root->left, low, high, answer); dfs(root->right, low, high, answer); } }; ``` ### Time Complexity $O(n)$ $n$ is the number of nodes in the binary tree referred by `root`. ### Space Complexity $O(H)$ $H$ is the height of the binary tree referred by `root`. ## C++ Code 2 ```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 { public: int rangeSumBST(TreeNode* root, int low, int high) { if (!root) { return 0; } if (root->val < low) { return rangeSumBST(root->right, low, high); } if (high < root->val) { return rangeSumBST(root->left, low, high); } return root->val + rangeSumBST(root->left, low, high) + rangeSumBST(root->right, low, high); } }; ``` ### Time Complexity $O(n)$ $n$ is the number of nodes in the binary tree referred by `root`. ### Space Complexity $O(H)$ $H$ is the height of the binary tree referred by `root`. # Miscellane <!-- # Test Cases ``` [10,5,15,3,7,null,18] 7 15 ``` ``` [10,5,15,3,7,13,18,1,null,6] 6 10 ``` -->