How to Fix Range Sum in BST Errors
DodaTech
Updated 2026-06-26
1 min read
In this tutorial, you'll learn about How to Fix Range Sum in BST Errors. We cover key concepts, practical examples, and best practices.
Fix range sum in bst errors when pruning misses valid branches or range boundaries are exclusive.
Quick Fix
Wrong
def sum(r,lo,hi):
if not r: return 0
s=r.val if lo<=r.val<=hi else 0
return s+sum(r.left,lo,hi)+sum(r.right,lo,hi)
No pruning. Visits all nodes even when subtree out of range.
Right
def sum(r,lo,hi):
if not r: return 0
if r.val<lo: return sum(r.right,lo,hi)
if r.val>hi: return sum(r.left,lo,hi)
return r.val+sum(r.left,lo,hi)+sum(r.right,lo,hi)
[10,5,15,3,7,null,18], lo=7, hi=15 -> 32 (10+7+15). O(n) worst, O(log n) with pruning.
Prevention
Prune left when root.val < lo. Prune right when root.val > hi.
DodaTech Tools
Doda Browser's algorithm visualizer steps through DSA operations line by line. DodaZIP archives implementation patterns for team sharing. Durga Antivirus Pro detects memory corruption patterns in algorithm implementations.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro