Problem Solving
100. Range Sum of BST
굥깡
2023. 1. 19. 20:28
728x90
https://leetcode.com/problems/range-sum-of-bst/description/
Range Sum of BST - LeetCode
Range Sum of BST - Given the root node of a binary search tree and two integers low and high, return the sum of values of all nodes with a value in the inclusive range [low, high]. Example 1: [https://assets.leetcode.com/uploads/2020/11/05/bst1.jpg] Inp
leetcode.com
Binary Search Tree를 훑으며 범위 내의 수들을 모두 더하는 문제
# 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:
next = None
sum = 0
nxt = [None]
while root != None:
if root.left != None:
if root.right != None:
next = root.right
nxt.append(next)
if root.val <= high and root.val >= low:
sum = sum + root.val
root = root.left
else:
if root.val <= high and root.val >= low:
sum = sum + root.val
root = nxt.pop()
return sum
Tree 구조(Class 안에 앞 뒤 노드들과 value를 정의하는 데이터 구조)에 익숙하지 않으니 상당히 어려웠다
풀었으니 다행인가 싶지만 더 깔끔한 방법이 있을 것 같다