leetcode 938: range sum of BST

wonderful world·2021년 12월 14일
0

leetcode

목록 보기
8/21

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

# 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 == None: return 0
        L = root.left
        R = root.right
        v = root.val
        
        # take node's value if it is in the range
        v = v if (low <= v <= high) else 0
        
        # recursively traverse children left and right 
        v_L = self.rangeSumBST(L, low, high)
        v_R = self.rangeSumBST(R, low, high)
        
        return v + v_L + v_R
            
profile
hello wirld

0개의 댓글