129 Sum Root to Leaf Numbers
Given a binary tree containing digits from0-9
only, each root-to-leaf path could represent a number.
An example is the root-to-leaf path1->2->3
which represents the number123
.
Find the total sum of all root-to-leaf numbers.
For example,
The root-to-leaf path1->2
represents the number12
.
The root-to-leaf path1->3
represents the number13
.
Return the sum = 12 + 13 =25
.
The Idea: Using a single DFS traversal, we can capture the elements as we iterate to build up a new string. Once a leaf is reached, we can push the collected string to a vector. Once we both left and right children are explored, we popback once to obtain an earlier state in the recursion of the string
Possible Improvements: We can maintain accumulate the elements immediately rather than storing them into a vector.
Last updated