Range Sum of BST — LeetCode 938 Python Solution

EasyTreeDepth-First SearchBinary Search TreeBinary Tree
Problem
#938
Reading time
4 min

The problem

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

Input
root = [10,5,15,3,7,null,18], low = 7, high = 15
Output
32
Explanation
Nodes 7, 10, and 15 are in the range [7, 15]. 7 + 10 + 15 = 32.

Python solution

Python
# 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:
        def dfs(root: Optional[TreeNode]) -> int:
            if root is None:
                return 0
            x = root.val
            ans = x if low <= x <= high else 0
            if x > low:
                ans += dfs(root.left)
            if x < high:
                ans += dfs(root.right)
            return ans

        return dfs(root)

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Tree Traversal

Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 938. Range Sum of BST is filed here because LeetCode tags it Tree, Binary Tree and Binary Search Tree, which is the vocabulary this hub collects.

The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 938. Range Sum of BST?
LeetCode 938. Range Sum of BST is rated Easy on LeetCode.
What is the time complexity of LeetCode 938. Range Sum of BST?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 938. Range Sum of BST?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 938. Range Sum of BST cover?
LeetCode 938. Range Sum of BST is tagged Tree, Depth-First Search, Binary Search Tree and Binary Tree on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview