public class Solution { /** * * @param root TreeNode类 * @return int整型 */ public int sumNumbers (TreeNode root) { // write code here List<List<Integer>> ans=new ArrayList<>(); List<Integer> path=new ArrayList<>(); backTrack(root,ans,path); int res=0; for(int i=0;i<ans.size();i++){ int sum=0; for(int j=0;j<ans.get(i).size();j++){ sum=sum*10+ans.get(i).get(j); } res+=sum; } return res; } void backTrack(TreeNode root,List<List<Integer>> ans,List<Integer> path){ if(root==null){ return; } path.add(root.val); if(root.left==null&&root.right==null){ ans.add(new ArrayList<>(path)); }else{ backTrack(root.left,ans,path); backTrack(root.right,ans,path); } path.remove(path.size()-1); } }