import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 * }
 */

public class Solution {

    private List<Integer> res = new ArrayList<>();

    /**
     * 
     * @param root TreeNode类 
     * @return int整型
     */
    public int sumNumbers (TreeNode root) {
        // write code here
        backtrack(root, new ArrayList<>());
        int sum = 0;
        for (int num : res) {
            sum += num;
        }
        return sum;
    }

    private void backtrack(TreeNode root, List<Integer> list) {
        if (root == null) {
            return;
        }
        list.add(root.val);
        if (root.left == null && root.right == null) {
            res.add(list2Int(new ArrayList<>(list)));
        }
        backtrack(root.left, list);
        backtrack(root.right, list);
        list.remove(list.size() - 1);
    }

    private int list2Int(List<Integer> list) {
        StringBuilder sb = new StringBuilder();
        for (int num : list) {
            sb.append(num);
        }
        return Integer.parseInt(sb.toString());
    }
}