Bluefissure's Blog

A Place for Recording

0%

LeetCode-938 Range Sum of BST

题目链接

题意

对BST在[L,R]区间的节点求和

思路

DFS

代码

1
2
3
4
5
6
7
8
9
class Solution:
def rangeSumBST(self, root, L, R):
if not root:
return 0
sumL = self.rangeSumBST(root.left,L,R) if root.left else 0
sumR = self.rangeSumBST(root.right,L,R) if root.right else 0
val = root.val if L <= root.val <= R else 0
return sumL+sumR+val