Problem
Given a binary tree containing digits from 0-9
only, each root-to-leaf path could represent a number.
An example is the root-to-leaf path 1->2->3
which represents the number 123
.
Find the total sum of all root-to-leaf numbers.
Note: A leaf is a node with no children.
Example:
1 |
|
Example 2:
1 |
|
Explanation
- We can use recursion method to solve. Whenever we encounted a root value, we will multiple the previous sum by 10 then add the current root value to become a new sum.
- We can think of the left node as a root, the right node as a root, then solve them recursivly and pass the new sum as left child and right child’s previous sum to the helper method to get their sums and add them both to become the root’s sum.
Solution
1 |
|