Solution
# Definition for a binary tree node.
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:
def dfs(node: TreeNode):
if not node:
return 0
# νμ¬ λ
Έλκ° lowλ³΄λ€ μμ κ²½μ°, λ μ΄μ μΌμͺ½ κ°μ§λ νμν νμκ° μμ
# μ¦, μ€λ₯Έμͺ½λ§ νμνλλ‘ μ¬κ· νΈμΆ
if node.val < low:
return dfs(node.right)
# μ΄κ²λ λ§μ°¬κ°μ§
elif node.val > high:
return dfs(node.left)
return node.val + dfs(node.left) + dfs(node.right)
return dfs(root)
Leave a comment