Sum Root to Leaf Numbers
Problem Statement
You are given the root of a binary tree. Every node holds one digit from 0 to 9.
Read a root-to-leaf path as a number, from top to bottom. For example, the path 1 → 2 → 3 is the number 123. Return the total of the numbers of all root-to-leaf paths. The tests are built so that the total fits in a 32-bit integer.
The root of a binary tree. It has at least one node, and each value is a digit from 0 to 9.
A single number: the total of all root-to-leaf numbers.
The paths read 12 (1 → 2) and 13 (1 → 3). 12 + 13 = 25.
The paths read 495 (4 → 9 → 5), 491 (4 → 9 → 1) and 40 (4 → 0). 495 + 491 + 40 = 1026.
- • The tree has between 1 and 1000 nodes.
- • 0 ≤ Node.val ≤ 9
- • The depth of the tree is at most 10.
- • The answer fits in a 32-bit integer.
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
Write each path down as digits, then convert each string to a number and add
Multiply the number so far by 10 and add the digit; add the number at each leaf
Walk the tree and add each node's digit to a string that is passed down. At each leaf, save the whole string. At the end, convert every saved string to an int with stoi and add them up.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Tree DFS translate into production architectures and low-level memory mechanics.
Foundations: Object-Oriented Principles in C++23
Class invariants, pure virtual interfaces, and RAII smart pointers.
Food Delivery System (Zomato Architecture)
Real-world machine coding application of algorithms and design patterns.
Pointers vs References Deep Dive
Pointer arithmetic and memory layout under the hood.
Virtual Method Table (vtable) & Memory Layout
Polymorphism, vptr overhead, and multiple inheritance in memory.