/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public int sumNumbers(TreeNode root) { ArrayList<Integer> result = new ArrayList<Integer>(); if(root == null) return 0; dfs(result, 0, root); int sum = 0; for(int i : result){ sum += i; } return sum; } private void dfs(ArrayList<Integer> result, int now, TreeNode root){ if(root.left == null && root.right == null){ result.add(10*now+root.val); } now = now*10+root.val;; if(root.left != null){ dfs(result, now, root.left); } if(root.right != null){ dfs(result, now, root.right); } } }