> ## Content Index
> Fetch the complete content index at: https://andybase.com/llms.txt
> Use this file to discover other available public pages before exploring further.

# 938 Range Sum of BST
- URL: https://andybase.com/938-range-sum-of-bst/
- Published: 2018-11-12T16:32:58.000Z
- Updated: 2018-11-12T16:32:58.000Z
- Author: andy
- Tags: leetcode, contest, #Migrated-1784083136856, #wp, #wp-post, #Import 2026-07-15 02:38

link: [Range Sum of BST](https://leetcode.com/problems/range-sum-of-bst/?ref=andybase.com)

## Thought

When first saw this question, I think using tree traverse could solve it and it did works.

## Code

```
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def rangeSumBST(self, root, L, R):
        """
        :type root: TreeNode
        :type L: int
        :type R: int
        :rtype: int
        """
        self.res = 0
        def helper(root): # helper function to traverse tree
            if not root:
                return
            if L <= root.val <= R:
                self.res += root.val
                helper(root.left)
                helper(root.right)
            elif root.val < L:
                helper(root.right)
            else:
                helper(root.left)
        helper(root)
        return self.res
```

## Runtime

Time O(n)  
Space O(n)