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
.
给定二叉搜索树的根结点 root
,返回 L
和 R
(含)之间的所有结点的值的和。
二叉搜索树保证具有唯一的值。
示例 1:
输入:root = [10,5,15,3,7,null,18], L = 7, R = 15 输出:32
示例 2:
输入:root = [10,5,15,3,7,13,18,1,null,6], L = 6, R = 10 输出:23
656ms
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * public var val: Int 5 * public var left: TreeNode? 6 * public var right: TreeNode? 7 * public init(_ val: Int) { 8 * self.val = val 9 * self.left = nil 10 * self.right = nil 11 * } 12 * } 13 */ 14 class Solution { 15 func rangeSumBST(_ root: TreeNode?, _ L: Int, _ R: Int) -> Int { 16 return dfs(root,L,R) 17 } 18 19 func dfs(_ root: TreeNode?, _ L: Int, _ R: Int) -> Int 20 { 21 if root == nil {return 0} 22 return dfs(root!.left, L, R) + dfs(root!.right, L, R) + (L <= root!.val && root!.val <= R ? root!.val : 0) 23 } 24 }