You are given the root of a binary tree containing digits from 0–9. Each root-to-leaf path represents a number (e.g., 1→2→3 = 123). Return the total sum of all root-to-leaf numbers.
root = [1,2,3]25root = [4,9,0,5,1]1026Multiplying by 10 and adding the next digit is exactly how decimal numbers are formed — curr = curr×10 + digit. At each leaf we have the complete root-to-leaf number. Summing the left and right DFS calls automatically accumulates all leaf contributions. No extra path storage needed.
You could build each path as a string and convert it at the leaf. Carrying the number as an integer is simpler and faster.
Carry the number formed so far, starting from 0. At each node, multiply it by 10 and add the node digit. At a leaf, that is one complete number, so return it. At other nodes, return the sum of the left and right results.
Times 10 plus the digit builds the number on the way down. Leaves return numbers, and parents add them up.
Run the animation above on your own input, or watch the 1:45 video explanation of Sum Root to Leaf Numbers with a dry run and Java code.