Sum Root to Leaf Numbers

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.

For example,

  1. 1
  2. / \
  3. 2 3

The root-to-leaf path 1->2 represents the number 12.
The root-to-leaf path 1->3 represents the number 13.

Return the sum = 12 + 13 = 25.

Solution:

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. public class Solution {
  11. int total;
  12. public int sumNumbers(TreeNode root) {
  13. total = 0;
  14. helper(root, 0);
  15. return total;
  16. }
  17. void helper(TreeNode root, int sum) {
  18. if (root == null) return;
  19. sum = sum * 10 + root.val;
  20. if (root.left == null && root.right == null) {
  21. total += sum;
  22. return;
  23. }
  24. helper(root.left, sum);
  25. helper(root.right, sum);
  26. }
  27. }