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); } }
点赞 1

相关推荐

01-24 12:50
门头沟学院 C++
投票
菜狗二号:还有啥想的 指定国有行啊,去了就开始幸福美满的生活了,选华子不是折腾自己么,最终财富积累度是差不多的,但是幸福指数是相差甚远的
点赞 评论 收藏
分享
牛客网
牛客企业服务