|
5 | 5 | import java.util.ArrayList;
|
6 | 6 | import java.util.List;
|
7 | 7 |
|
8 |
| -/** |
9 |
| - * 113. Path Sum II |
10 |
| -
|
11 |
| - Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum. |
12 |
| -
|
13 |
| -For example: |
14 |
| -Given the below binary tree and sum = 22, |
15 |
| - 5 |
16 |
| - / \ |
17 |
| - 4 8 |
18 |
| - / / \ |
19 |
| - 11 13 4 |
20 |
| - / \ / \ |
21 |
| - 7 2 5 1 |
22 |
| -
|
23 |
| - return |
24 |
| -[ |
25 |
| - [5,4,11,2], |
26 |
| - [5,8,4,5] |
27 |
| -] |
28 |
| -*/ |
29 | 8 | public class _113 {
|
30 | 9 |
|
31 |
| - public static class Solution1 { |
32 |
| - public List<List<Integer>> pathSum(TreeNode root, int sum) { |
33 |
| - List<List<Integer>> allPaths = new ArrayList(); |
34 |
| - if (root == null) { |
35 |
| - return allPaths; |
36 |
| - } |
37 |
| - dfs(root, new ArrayList(), allPaths, sum); |
38 |
| - return allPaths; |
39 |
| - } |
| 10 | + public static class Solution1 { |
| 11 | + public List<List<Integer>> pathSum(TreeNode root, int sum) { |
| 12 | + List<List<Integer>> allPaths = new ArrayList(); |
| 13 | + if (root == null) { |
| 14 | + return allPaths; |
| 15 | + } |
| 16 | + dfs(root, new ArrayList(), allPaths, sum); |
| 17 | + return allPaths; |
| 18 | + } |
40 | 19 |
|
41 |
| - private void dfs(TreeNode root, List<Integer> path, List<List<Integer>> allPaths, int sum) { |
42 |
| - path.add(root.val); |
43 |
| - if (root.left != null) { |
44 |
| - dfs(root.left, path, allPaths, sum - root.val); |
45 |
| - } |
46 |
| - if (root.right != null) { |
47 |
| - dfs(root.right, path, allPaths, sum - root.val); |
48 |
| - } |
49 |
| - if (root.left == null && root.right == null) { |
50 |
| - /**Check if sum equals root.val, not sum equals zero!*/ |
51 |
| - if (sum == root.val) { |
52 |
| - allPaths.add(new ArrayList(path)); |
| 20 | + private void dfs(TreeNode root, List<Integer> path, List<List<Integer>> allPaths, int sum) { |
| 21 | + path.add(root.val); |
| 22 | + if (root.left != null) { |
| 23 | + dfs(root.left, path, allPaths, sum - root.val); |
| 24 | + } |
| 25 | + if (root.right != null) { |
| 26 | + dfs(root.right, path, allPaths, sum - root.val); |
| 27 | + } |
| 28 | + if (root.left == null && root.right == null) { |
| 29 | + /**Check if sum equals root.val, not sum equals zero!*/ |
| 30 | + if (sum == root.val) { |
| 31 | + allPaths.add(new ArrayList(path)); |
| 32 | + } |
| 33 | + } |
| 34 | + path.remove(path.size() - 1); |
53 | 35 | }
|
54 |
| - } |
55 |
| - path.remove(path.size() - 1); |
56 | 36 | }
|
57 |
| - } |
58 | 37 | }
|
0 commit comments