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].

A Binary Search Tree (BST) is a tree where for every node, all values in the left subtree are smaller than the node's value, and all values in the right subtree are greater than the node's value.

Input & Output

Example 1 — Basic BST
$ Input: root = [10,5,15,3,7,null,18], low = 7, high = 15
Output: 32
💡 Note: Nodes 7, 10, and 15 are in range [7,15]. Sum = 7 + 10 + 15 = 32
Example 2 — Smaller Range
$ Input: root = [10,5,15,3,7,13,18,1,null,6], low = 6, high = 10
Output: 23
💡 Note: Nodes 6, 7, and 10 are in range [6,10]. Sum = 6 + 7 + 10 = 23
Example 3 — Single Node
$ Input: root = [5], low = 3, high = 8
Output: 5
💡 Note: Only node 5 exists and it's in range [3,8]. Sum = 5

Constraints

  • The number of nodes in the tree is in the range [1, 2 × 104]
  • 1 ≤ Node.val ≤ 105
  • 1 ≤ low ≤ high ≤ 105

Visualization

Tap to expand
Range Sum of BST INPUT Binary Search Tree 10 5 15 3 7 18 In range [7,15] Out of range root = [10,5,15,3,7,null,18] low = 7, high = 15 Range: [7, 15] inclusive bounds ALGORITHM STEPS DFS with BST Pruning 1 Check Current Node If node.val in [low,high] add to sum 2 Prune Left Subtree Only traverse left if node.val > low 3 Prune Right Subtree Only traverse right if node.val < high 4 Sum Results Return sum of current + left + right subtrees Calculation: Node 10: 7 <= 10 <= 15 [OK] Node 7: 7 <= 7 <= 15 [OK] Node 15: 7 <= 15 <= 15 [OK] Sum = 10 + 7 + 15 = 32 FINAL RESULT Nodes in range [7,15]: 7 10 15 + + Output: 32 [OK] Verified 7 + 10 + 15 = 32 Pruned Nodes: 3 (less than low) 5 (less than low) 18 (greater than high) Key Insight: BST property enables smart pruning: skip left subtree if node <= low (all left values smaller), skip right subtree if node >= high (all right values larger). This reduces time from O(n) to O(h + k) where h is tree height and k is count of nodes in range. Avoid unnecessary traversals! TutorialsPoint - Range Sum of BST | Optimized DFS with BST Pruning
Asked in
Facebook 45 Amazon 32 Microsoft 28 Google 25
125.0K Views
Medium Frequency
~15 min Avg. Time
3.4K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen