Given the `root` node of a binary search tree, return the sum of values of all nodes with value between `L` and `R` (inclusive).
The binary search tree is guaranteed to have unique values.
Example 1:
Input: root = [10,5,15,3,7,null,18], L = 7, R = 15
Output: 32
Example 2:
Input: root = [10,5,15,3,7,13,18,1,null,6], L = 6, R = 10
Output: 23
Note:
- The number of nodes in the tree is at most
10000
. - The final answer is guaranteed to be less than
2^31
.
這道題給了一棵二叉搜索樹,還給了兩個整型數L和R,讓返回所有結點值在區間 [L, R] 內的和,就是說找出所有的在此區間內的結點,將其所有結點值累加起來返回即可。最簡單粗暴的思路就是遍歷所有的結點,對每個結點值都檢測其是否在區間內,是的話就累加其值,最后返回累加和即可,參見代碼如下:
解法一:
class Solution {
public:
int rangeSumBST(TreeNode* root, int L, int R) {
int res = 0;
helper(root, L, R, res);
return res;
}
void helper(TreeNode* node, int L, int R, int& res) {
if (!node) return;
if (node->val >= L && node->val <= R) res += node->val;
helper(node->left, L, R, res);
helper(node->right, L, R, res);
}
};
上面的解法雖然能過,但不是最優解,因為並沒有利用到二叉搜索樹的性質,由於 BST 具有 左<根<右 的特點,所以就可以進行剪枝,若當前結點值小於L,則說明其左子樹所有結點均小於L,可以直接將左子樹剪去;同理,若當前結點值大於R,則說明其右子樹所有結點均大於R,可以直接將右子樹剪去。否則說明當前結點值正好在區間內,將其值累加上,並分別對左右子結點調用遞歸函數即可,參見代碼如下:
解法二:
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, R) + rangeSumBST(root->right, L, R);
}
};
Github 同步地址:
https://github.com/grandyang/leetcode/issues/938
參考資料:
https://leetcode.com/problems/range-sum-of-bst/
https://leetcode.com/problems/range-sum-of-bst/discuss/205181/Java-4-lines-Beats-100
[LeetCode All in One 題目講解匯總(持續更新中...)](https://www.cnblogs.com/grandyang/p/4606334.html)