Solution 1 - DFS with BST Pruning
If node.val < low, skip left subtree; if node.val > high, skip right subtree.
If node.val < low, skip left subtree; if node.val > high, skip right subtree.
""" 0938.1 - Range Sum of BST - Solution 1 - DFS with Pruning """
from typing import Optional
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 < low:
return self.rangeSumBST(root.right, low, high)
if root.val > high:
return self.rangeSumBST(root.left, low, high)
return root.val + self.rangeSumBST(root.left, low, high) + self.rangeSumBST(root.right, low, high)