반응형
난이도 - Easy
Intuition
DFS로 탐색하며 값을 비교하면서 풀 수 있는 문제이다.
또한 BST이기 때문에 현재 node의 val이 low보다 크면 왼쪽 child를 탐색하고, node의 val이 high보다 작으면 오른쪽 child를 탐색하면 시간을 줄일 수 있다.
Code
# Recursive
# 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:
ans = 0
def dfs(node):
if not node:
return
nonlocal ans
val = node.val
if low <= val <= high:
ans += val
if val > low:
dfs(node.left)
if val < high:
dfs(node.right)
dfs(root)
return ans
# Iterative
class Solution:
def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int:
ans = 0
stack = [root]
while stack:
node = stack.pop()
if node:
val = node.val
if low <= val <= high:
ans += val
if low < val:
stack.append(node.left)
if val < high:
stack.append(node.right)
return ans
Complexity
Time Complexity: O(n) 여기서 n은 Tree의 node 개수이다
Space Complexity: O(n) dfs이기 때문에 function call stack을 유지하고 있으므로 이때의 worst case는 O(n)이다.
반응형
'코딩 알고리즘 문제 > Leetcode' 카테고리의 다른 글
| 50. Pow(x, n) (Math, Recursion) (0) | 2025.10.17 |
|---|---|
| 973. K Closest Points to Origin (Array, Math, Divide and Conquer, Geometry, Sorting, Heap (Priority Queue), Quickselect) (0) | 2025.10.17 |
| 408. Valid Word Abbreviation (Two Pointers, String) (0) | 2025.10.17 |
| 1249. Minimum Remove to Make Valid Parentheses (String, Stack) (0) | 2025.10.17 |
| 314. Binary Tree Vertical Order Traversal (0) | 2025.10.17 |