标题: | Path Sum II |
通过率: | 26.7% |
难度: | 中等 |
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
For example:
Given the below binary tree and sum = 22
,
5 / 4 8 / / 11 13 4 / / 7 2 5 1
return
[ [5,4,11,2], [5,8,4,5] ]
与第一个版本一样,但是本次要求的是讲所以可能全部输出,那么就需要一个临时的list去保存,如果不等于则弹出最后一个。
具体代码:
1 /** 2 * Definition for binary tree 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 public ArrayList<ArrayList<Integer>> pathSum(TreeNode root, int sum) { 12 ArrayList<ArrayList<Integer>> res=new ArrayList<ArrayList<Integer>>(); 13 ArrayList<Integer> tmp=new ArrayList<Integer>(); 14 int sumtmp=0; 15 dfs(res,tmp,root,sum,sumtmp); 16 return res; 17 } 18 public void dfs(ArrayList<ArrayList<Integer>> res,ArrayList<Integer> tmp,TreeNode root, int sum,int sumtmp){ 19 if(root==null) return; 20 sumtmp+=root.val; 21 tmp.add(root.val); 22 if(root.left==null&&root.right==null&&sumtmp==sum){ 23 res.add(new ArrayList<Integer>(tmp)); 24 } 25 if(root.left!=null) dfs(res,tmp,root.left,sum,sumtmp); 26 if(root.right!=null)dfs(res,tmp,root.right,sum,sumtmp); 27 sumtmp-=root.val; 28 tmp.remove(tmp.size()-1); 29 } 30 }