Published:
Updated:


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