共计 680 个字符,预计需要花费 2 分钟才能阅读完成。
1. 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. #### 1. 例子
Input: root = [10,5,15,3,7,null,18], L = 7, R = 15
Output: 32
Input: root = [10,5,15,3,7,13,18,1,null,6], L = 6, R = 10
Output: 23
2. 我的解法
var rangeSumBST = function(root, L, R) {
let sum =0
sum = bstSun(sum, L, R, root)
return sum
};
var bstSun = function(sum, L, R, node) {
if(node !== null) {
if(node.val<=R&&node.val>=L){
sum += node.val
}
sum = bstSun(sum, L, R, node.left)
sum = bstSun(sum, L, R, node.right)
}
return sum
}
3. 其他解法
class Solution:
def rangeSumBST(self, root, L, R):
if not root: return 0
l = self.rangeSumBST(root.left, L, R)
r = self.rangeSumBST(root.right, L, R)
return l + r + (L <= root.val <= R) * root.val