KK's blog

每天积累多一些

0%

LeetCode 938 Range Sum of BST

LeetCode



Given the root node of a binary search tree and two integers low and high, return the sum of values of all nodes with a value in the inclusive range [low, high].

Example 1:



Input: root = [10,5,15,3,7,null,18], low = 7, high = 15
Output: 32
Explanation: Nodes 7, 10, and 15 are in the range [7, 15]. 7 + 10 + 15 = 32.


Example 2:



Input: root = [10,5,15,3,7,13,18,1,null,6], low = 6, high = 10
Output: 23
Explanation: Nodes 6, 7, and 10 are in the range [6, 10]. 6 + 7 + 10 = 23.


Constraints:

The number of nodes in the tree is in the range `[1, 2 104]. *1 <= Node.val <= 105*1 <= low <= high <= 105* AllNode.val` are unique.

题目大意:

给定[low, high]和BST,求满足条件的BST的节点和

解题思路:

Easy题,DFS,条件比较容易错

解题步骤:

N/A

注意事项:

  1. 两个条件,若root.val在范围内,加入和。若low小于root.val(这里不取等号,因为所有节点是唯一,不存在相等节点),
    表示范围适用于左节点,同理右节点。

Python代码:

1
2
3
4
5
6
7
8
9
10
11
def rangeSumBST(self, root: TreeNode, low: int, high: int) -> int:
if not root:
return 0
res = 0
if low <= root.val <= high:
res += root.val
if low < root.val:
res += self.rangeSumBST(root.left, low, high)
if root.val < high:
res += self.rangeSumBST(root.right, low, high)
return res

算法分析:

时间复杂度为O(n),空间复杂度O(1)

Free mock interview