Star

LeetCode 113.Path Sum II

Question

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,

1
2
3
4
5
6
7
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1

return

1
2
3
4
[
[5,4,11,2],
[5,8,4,5]
]

Explanation

递归的时候保留路径,满足就存入全局变量中。

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
private List<List<Integer>> resultList = new ArrayList<List<Integer>>();
public void pathSumHelper(TreeNode root, int sum, ArrayList<Integer> path){
path.add(root.val);
if (root == null) return;
if (root.left == null && root.right == null) {
if (root.val== sum) {
resultList.add(new ArrayList<Integer>(path));
}
}
if (root.left != null) pathSumHelper(root.left, sum - root.val, path);
if (root.right != null) pathSumHelper(root.right, sum - root.val, path);
path.remove(path.size()-1);
}
public List<List<Integer>> pathSum(TreeNode root, int sum) {
if(root==null) return resultList;
ArrayList<Integer> path = new ArrayList<>();
pathSumHelper(root, sum, path);
return resultList;
}
}