-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path113. Path Sum II (DFS) 20.3.18 Medium
More file actions
82 lines (73 loc) · 2.23 KB
/
113. Path Sum II (DFS) 20.3.18 Medium
File metadata and controls
82 lines (73 loc) · 2.23 KB
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
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,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
Return:
[
[5,4,11,2],
[5,8,4,5]
]
Solution: -------------------------------------------------- DFS
------------------------------------------------------------ O(n) T, O(n) S
class Solution(object):
def pathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: List[List[int]]
"""
if root is None:
return []
res = []
self.dfs(root, sum, [], res)
return res
def dfs(self, root, sum, path, res):
if not root:
return
if not root.left and not root.right and sum == root.val:
res.append(path + [root.val])
self.dfs(root.left, sum - root.val, path + [root.val], res) # How to concatenate int to list !!!!
# Use path instead of currlist.append() + currlist.pop()
self.dfs(root.right, sum - root.val, path + [root.val], res)
Java Version:
/**
* 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) {
if (root == null) {
return new ArrayList<>();
}
List<List<Integer>> res = new ArrayList<>();
dfs(root, sum, new ArrayList<>(), res);
return res;
}
public void dfs(TreeNode root, int sum, List<Integer> path, List<List<Integer>> res) {
if (root == null) {
return;
}
if (root.left == null && root.right == null && root.val == sum) {
path.add(root.val);
res.add(new ArrayList<>(path));
path.remove(path.size() - 1);
return;
}
path.add(root.val);
dfs(root.left, sum - root.val, path, res);
dfs(root.right, sum - root.val, path, res);
path.remove(path.size() - 1);
}
}