#938
Range Sum of BST
EasyTreeDepth-First SearchBinary Search TreeBinary TreeDepth-First Search (DFS)RecursionBinary Search Tree properties
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(h) |
💡
Intuition
Time O(n)Space O(h)
The optimal solution leverages the properties of a binary search tree (BST) to skip unnecessary nodes. Instead of visiting every node, we can make decisions based on the current node's value, allowing us to reduce the number of nodes we need to check.
⚙️
Algorithm
5 steps- 1Step 1: Start from the root of the BST.
- 2Step 2: If the current node's value is less than low, move to the right child (all values to the left are too small).
- 3Step 3: If the current node's value is greater than high, move to the left child (all values to the right are too large).
- 4Step 4: If the current node's value is within the range [low, high], add it to the sum and check both children.
- 5Step 5: Continue this process until all relevant nodes are checked.
solution.py16 lines
1# Full working Python code
2class TreeNode:
3 def __init__(self, val=0, left=None, right=None):
4 self.val = val
5 self.left = left
6 self.right = right
7
8def rangeSumBST(root, low, high):
9 if not root:
10 return 0
11 if root.val < low:
12 return rangeSumBST(root.right, low, high)
13 elif root.val > high:
14 return rangeSumBST(root.left, low, high)
15 else:
16 return root.val + rangeSumBST(root.left, low, high) + rangeSumBST(root.right, low, high)ℹ
Complexity note: The time complexity is O(n) in the worst case (when the tree is unbalanced), but on average, it can be O(log n) for balanced trees. The space complexity is O(h) due to the recursion stack, where h is the height of the tree.
- 1Utilizing the properties of a BST can significantly reduce the number of nodes we need to check.
- 2Recursive traversal can be optimized by avoiding unnecessary branches.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.