← Accenture bank

Accenture · Question 48 · Trees

Path Sum

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

Problem

Given a binary tree and a sum, determine if the tree has a root - to - leaf path such that adding up all values equals the sum.

Approach

DFS through the tree subtracting current node value from sum, check leaf nodes.

Time O(n)Space O(h)

How it works

  1. 1Subtract node values down the path.
  2. 2Only a matching leaf completes it.

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 sum)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