m1ndy5's coding blog

LeetCode 938. Range Sum of BST with Python 본문

알고리즘 with python/알고리즘 스터디

LeetCode 938. Range Sum of BST with Python

정민됴 2024. 1. 12. 10:41

https://leetcode.com/problems/range-sum-of-bst/description/

# 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:
        answer = [0]

        def dfs(node, low, high):

            if not node:
                return
            # low 넘버보다 작은데 오른쪽 노드가 있으면 오른쪽으로 가기
            if node.val < low and node.right:
                dfs(node.right, low, high)

            # high 넘버보다 큰데 왼쪽 노드가 있으면 왼쪽으로 가기
            elif node.val > high and node.left:
                dfs(node.left, low, high)

            # 사이값이거나 같을 때 그 값을 더하고 양쪽 써칭
            elif node.val >= low and node.val <= high:
                answer[0] += node.val
                dfs(node.left, low, high)
                dfs(node.right, low, high)

        dfs(root, low, high)

        return answer[0]

이진탐색 트리였기 때문에 이진탐색하듯이 low보다 작아? 그럼 오른쪽으로 가 high 보다 커? 그럼 왼쪽으로 가
이런 식으로 써칭하고 만약에 해당하는 값이거나 사이값일 경우 양쪽 다 확인해! 하는 문제였다!