← Capgemini bank

Capgemini · Question 47 · Trees

Range Sum of BST

TreesC++code⏱ O(n)💾 O(h)
Service-based

Problem

You are given BST root and range [low, high]. Find sum of values in range.

Approach

Add in-range values; prune subtrees that cannot contain any.

Time O(n)Space O(h)

How it works

  1. 1Add the node when it falls inside [low, high].
  2. 2Skip the left subtree when node <= low; skip right when node >= high.

Sample input / output

Input:
root = [10, 5, 15, 3, 7, null, 18], low = 7, high = 15
Output:
32

Constraints

1 <= nodes <= 2 * 10^4.

Solution — read it, then walk it

Time O(n)Space O(h)Branches 4Returns 2source · C++
Scroll sideways for wide charts — the view follows the active step.
yesnoyesnoyesnoSTARTinclude <iostream>include <vector>include <climits>using namespace stdCLASS TreeNodeDEFINE valTreeNode *left, *rightTreeNode(int x) : val(x),left(nullptr),right(nullptr) {}TreeNode* buildTree(constvector<int>& vs, intnullMark = INT_MIN)DEFINErangeSumBST(TreeNode* root,int low, int high)if (!root) return 0DEFINE sum = 0if (root->val >= low&& root->val <= high)sum += root->valif (root->val > low)sum +=rangeSumBST(root->left,low, high)if (root->val < high)sum +=rangeSumBST(root->right,low, high)RETURN sumDEFINE main()cout <<rangeSumBST(buildTree({10,5, 15, 3, 7, INT_MIN, 18})…RETURN 0END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/23

StartSTART

Interactive control-flow diagram and step-by-step code walkthrough.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits