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] ]
This is a follow up question of Path Sum. Note that the values along the path may contain negative values.
Java语言: PathSumII
01 public ArrayList<ArrayList<Integer>> pathSum(TreeNode root, int sum) {
02 ArrayList<ArrayList<Integer>>results=new ArrayList<ArrayList<Integer>>();
03 ArrayList<Integer> temp=new ArrayList<Integer>();
04 findPath(results,temp,root,sum);
05 return results;
06
07 }
08 public void findPath(ArrayList<ArrayList<Integer>>results,ArrayList<Integer>temp,TreeNode root, int sum)
09 {
10 if(root==null)
11 return;
12 if(root.val==sum && root.left==null && root.right==null)
13 {
14 temp.add(root.val);
15 ArrayList<Integer>out=new ArrayList<Integer>();
16 for(int i=0;i<temp.size();i++)
17 {
18 out.add(temp.get(i));
19 }
20 results.add(out);
21 }
22 else
23 {
24 temp.add(root.val);
25 findPath(results,temp,root.left,sum-root.val);
26 findPath(results,temp,root.right,sum-root.val);
27 }
28 int size=temp.size();
29 if(size>0)
30 {
31 temp.remove(size-1);
32 }
33
34 }
02 ArrayList<ArrayList<Integer>>results=new ArrayList<ArrayList<Integer>>();
03 ArrayList<Integer> temp=new ArrayList<Integer>();
04 findPath(results,temp,root,sum);
05 return results;
06
07 }
08 public void findPath(ArrayList<ArrayList<Integer>>results,ArrayList<Integer>temp,TreeNode root, int sum)
09 {
10 if(root==null)
11 return;
12 if(root.val==sum && root.left==null && root.right==null)
13 {
14 temp.add(root.val);
15 ArrayList<Integer>out=new ArrayList<Integer>();
16 for(int i=0;i<temp.size();i++)
17 {
18 out.add(temp.get(i));
19 }
20 results.add(out);
21 }
22 else
23 {
24 temp.add(root.val);
25 findPath(results,temp,root.left,sum-root.val);
26 findPath(results,temp,root.right,sum-root.val);
27 }
28 int size=temp.size();
29 if(size>0)
30 {
31 temp.remove(size-1);
32 }
33
34 }
In line 15-19, why need to copy tmp to a new ArrayList out?
回复删除Using new ArrayList(temp) to initialize the out instead of the for loop makes code more concise.
回复删除