You are 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 = [5,3,8,1,4,7,9,null,2], low = 3, high = 8
Output: 27Explanation: Nodes 5, 3, 8, 4 and 7 are in the range [3, 8]. 5 + 3 + 8 + 4 + 7 = 27.
Example 2:
Input: root = [4,3,5,2,null], low = 2, high = 4
Output: 9Explanation: Nodes 4, 3, and 2 are in the range [2, 4]. 4 + 3 + 2 = 9.
Constraints:
1 <= The number of nodes in the tree <= 20,000.1 <= Node.val, low, high <= 100,000Node.val are unique.# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int:
if not root:
return 0
res = root.val if low <= root.val <= high else 0
res += self.rangeSumBST(root.left, low, high)
res += self.rangeSumBST(root.right, low, high)
return res# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int:
if not root:
return 0
if root.val > high:
return self.rangeSumBST(root.left, low, high)
if root.val < low:
return self.rangeSumBST(root.right, low, high)
return (
root.val +
self.rangeSumBST(root.left, low, high) +
self.rangeSumBST(root.right, low, high)
)# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int:
stack = [root]
res = 0
while stack:
node = stack.pop()
if not node:
continue
if low <= node.val <= high:
res += node.val
if node.val > low:
stack.append(node.left)
if node.val < high:
stack.append(node.right)
return res