Skip to content

Commit b9b46bc

Browse files
author
applewjg
committed
path sum2
Change-Id: I53f9100815f68d914630525e4dd897f3b9715757
1 parent bd9d3f6 commit b9b46bc

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

PathSum2.java

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
/*
2+
Author: King, [email protected]
3+
Date: Oct 7, 2014
4+
Problem: Path Sum 2
5+
Difficulty: easy
6+
Source: https://oj.leetcode.com/problems/path-sum-ii/
7+
Notes:
8+
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
9+
10+
For example:
11+
Given the below binary tree and sum = 22,
12+
5
13+
/ \
14+
4 8
15+
/ / \
16+
11 13 4
17+
/ \ / \
18+
7 2 5 1
19+
return
20+
[
21+
[5,4,11,2],
22+
[5,8,4,5]
23+
]
24+
25+
Solution: DFS.
26+
*/
27+
28+
/**
29+
* Definition for binary tree
30+
* public class TreeNode {
31+
* int val;
32+
* TreeNode left;
33+
* TreeNode right;
34+
* TreeNode(int x) { val = x; }
35+
* }
36+
*/
37+
public class Solution {
38+
public List<List<Integer>> pathSum(TreeNode root, int sum) {
39+
List<List<Integer>> res = new ArrayList<List<Integer>>();
40+
ArrayList<Integer> path = new ArrayList<Integer>();
41+
pathSumRe(root, sum, res, path);
42+
return res;
43+
}
44+
public void pathSumRe(TreeNode root, int sum, List<List<Integer>> res, ArrayList<Integer> path)
45+
{
46+
if (root == null) return;
47+
path.add(root.val);
48+
if (root.left == null && root.right == null && root.val == sum){
49+
ArrayList<Integer> tmp = new ArrayList<Integer>(path);
50+
res.add(tmp);
51+
}
52+
pathSumRe(root.left, sum - root.val, res, path);
53+
pathSumRe(root.right, sum - root.val, res, path);
54+
path.remove(path.size()-1);
55+
}
56+
}
57+

0 commit comments

Comments
 (0)