BST

LeetCode 938 Range Sum of BST (Python)

Posted by 小明MaxMing on November 15, 2020

题目

Given the root node of a binary search tree, return the sum of values of all nodes with a value in the range [low, high].

解题思路

递归,如果当前节点在范围内,加到结果里。如果当前节点大于low,遍历左子树,小于high,遍历右子树

代码

class Solution:
    class Solution:
    def rangeSumBST(self, root: TreeNode, low: int, high: int) -> int:
        def dfs(root):
            if root:
                if low <= root.val <= high:
                    self.res += root.val
                if low < root.val:
                    dfs(root.left)
                if high > root.val:
                    dfs(root.right)
        self.res = 0
        dfs(root)
        return self.res

视频讲解 YouTube<--欢迎点击订阅

视频讲解 bilibili<--欢迎点击订阅