본문 바로가기
👩‍💻Developer/Leetcode

[Easy][Python] Range Sum of BST

by 블루누들 2022. 10. 28.

Binary search tree라는 root와 low, high range가 주어졌을 때 [low, high] 안에 포함되는 모든 노드 값의 합을 return 한다

 

# 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:
        if root is None: return 0
        elif root.val > high: 
            return self.rangeSumBST(root.left,low,high) #recursive within the class
        elif root.val < low:
            return self.rangeSumBST(root.right,low,high)
        else:
            return root.val + self.rangeSumBST(root.left, low,high) + self.rangeSumBST(root.right,low,high)

댓글