← Accenture bank

Accenture · Question 53 · Trees

Path Sum III

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

Problem

Find the number of paths that sum to a given value in a binary tree. Paths do not need to start at root or end at leaf but must go downwards.

Approach

DFS with prefix sums stored in a hashmap to count paths efficiently.

Time O(n)Space O(n)

How it works

  1. 1Track running sums from the root.
  2. 2curr - target seen before means paths ending here hit it.

Sample input / output

Input:
root = [10, 5, -3, 3, 2, null, 11, 3, -2, null, 1], targetSum = 8
Output:
3

Constraints

0 <= nodes <= 1000; -10^9 <= Node.val <= 10^9.

Solution — read it, then walk it

Time O(n)Space O(n)Loops 1Branches 2Returns 3source · C++
Scroll sideways for wide charts — the view follows the active step.
↻ repeatSTARTinclude <iostream>include <vector>include <unordered_map>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 << "]" << endlDEFINE dfs(TreeNode* node,long long curr, int target,unordered_map<long long…DEFINE pathSum(TreeNode*root, int targetSum)unordered_map<long long,int> prefixprefix[0] = 1RETURN dfs(root, 0,targetSum, prefix)DEFINE dfs(TreeNode* node,long long curr, int target,unordered_map<long long…if (!node) return 0curr += node->valDEFINE count =prefix.count(curr - target)? prefix[curr - target] : 0prefix[curr]++count += dfs(node->left,curr, target, prefix)count += dfs(node->right,curr, target, prefix)prefix[curr]--RETURN countDEFINE main()vector<int> vs = {10, 5,-3, 3, 2, INT_MIN, 11, 3,-2, INT_MIN, 1}cout <<pathSum(buildTree(vs), 8)<< endlRETURN 0END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/35

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