Loading problem...
You are provided with the root node of a binary tree where every node contains a single digit value ranging from 0 to 9.
Each path traversing from the root node down to any leaf node forms a decimal number by concatenating the digit values encountered along the way. For instance, a path containing nodes with values 4, 7, and 2 (in that order from root to leaf) represents the decimal number 472.
Your task is to calculate and return the cumulative sum of all such numbers formed by every distinct root-to-leaf path in the tree.
A leaf node is defined as a node that has no children (both left and right child references are null).
The input guarantees that the resulting sum will always fit within the bounds of a 32-bit signed integer.
root = [1,2,3]25The tree has two root-to-leaf paths: • Path 1 → 2 forms the number 12 • Path 1 → 3 forms the number 13 Therefore, the total sum = 12 + 13 = 25.
root = [4,9,0,5,1]1026The tree has three root-to-leaf paths: • Path 4 → 9 → 5 forms the number 495 • Path 4 → 9 → 1 forms the number 491 • Path 4 → 0 forms the number 40 Therefore, the total sum = 495 + 491 + 40 = 1026.
root = [1,2,null,3]123The tree has only one root-to-leaf path: 1 → 2 → 3, which forms the number 123.
Constraints