kniost

谁怕,一蓑烟雨任平生

0%

LeetCode 113. Path Sum II

113. Path Sum II

Difficulty:: Medium

Given a binary tree and a sum, find all root-to-leaf paths where each path’s sum equals the given sum.

Note: A leaf is a node with no children.

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]
]

Solution

Language: Java

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
37
38
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> result = new ArrayList<>();
if (root == null) {
return result;
}
List<Integer> path = new ArrayList<>();
path.add(root.val);
pathHelper(root, sum - root.val, path, result);
return result;
}

private void pathHelper(TreeNode root, int sum, List<Integer> path, List<List<Integer>> result) {
if (root.left == null && root.right == null && sum == 0) {
result.add(new ArrayList<>(path));
}
if (root.left != null) {
path.add(root.left.val);
pathHelper(root.left, sum - root.left.val, path, result);
path.remove(path.size() - 1);
}
if (root.right != null) {
path.add(root.right.val);
pathHelper(root.right, sum - root.right.val, path, result);
path.remove(path.size() - 1);
}

}
}
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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> result = new ArrayList<>();
dfsHelper(root, sum, result, new ArrayList<>());
return result;
}

private void dfsHelper(TreeNode root, int sum, List<List<Integer>> result, List<Integer> one) {
if (root == null) {
return;
}
one.add(root.val);
if (root.left == null && root.right == null && sum == root.val) {
result.add(new ArrayList<>(one));
one.remove(one.size() - 1);
return;
}
dfsHelper(root.left, sum - root.val, result, one);
dfsHelper(root.right, sum - root.val, result, one);
one.remove(one.size() - 1);
}
}