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)
'👩💻Developer > Leetcode' 카테고리의 다른 글
[Easy][Python] Palindrome Number (0) | 2022.12.01 |
---|---|
[Easy][Python] Check if Two String Arrays are Equivalent (0) | 2022.11.20 |
[Easy][Python] Root Equals Sum of Children (0) | 2022.10.25 |
[Easy][Python] Count of Matches in Tournament (0) | 2022.10.23 |
[Easy][Python] Defanging an IP Address (0) | 2022.10.23 |
댓글