← Capgemini bank

Capgemini · Question 54 · Trees

Path Sum

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

Problem

You are given root and target sum. Check if there's root-to-leaf path summing to target.

Approach

Subtract node values along the way; a leaf must match the remainder exactly.

Time O(n)Space O(h)

How it works

  1. 1Carry the remaining sum downward.
  2. 2Only a matching leaf completes the path.

Sample input / output

Input:
root = [5, 4, 8, 11, null, 13, 4, 7, 2, null, null, null, 1], targetSum = 22
Output:
true

Constraints

0 <= nodes <= 5000.

Solution — read it, then walk it

Time O(n)Space O(h)Loops 1Branches 1Returns 1source · C++
Scroll sideways for wide charts — the view follows the active step.
↻ repeatSTARTinclude <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)DEFINE printVec(constvector<int>& v)cout << "["for (size_t i = 0; i <v.size(); ++i)if (i) cout << ", "cout << v[i]cout << "]" << endlbool hasPathSum(TreeNode*root, int targetSum)DEFINE main()vector<int> vs = {5, 4, 8,11, INT_MIN, 13, 4, 7, 2,INT_MIN, INT_MIN, INT_MIN…cout << boolalpha <<hasPathSum(buildTree(vs),22) << endlRETURN 0END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/21

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