forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
PathSumII.swift
48 lines (40 loc) · 1.39 KB
/
PathSumII.swift
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
/**
* Question Link: https://leetcode.com/problems/path-sum-ii/
* Primary idea: recursion
*
* Note: Structs in Swift are passed by value. Classes are passed by reference. Array and Dictionaryin Swift * are implemented as structs. In order to pass the array by reference, use inout to declare the variable.
*
* Time Complexity: O(n), Space Complexity: O(n)
*
* Definition for a binary tree node.
* public class TreeNode {
* public var val: Int
* public var left: TreeNode?
* public var right: TreeNode?
* public init(_ val: Int) {
* self.val = val
* self.left = nil
* self.right = nil
* }
* }
*/
class PathSumII {
func pathSum(_ root: TreeNode?, _ sum: Int) -> [[Int]] {
var paths = [[Int]](), path = [Int]()
dfs(root, sum, &paths, &path)
return paths
}
fileprivate func dfs(_ root: TreeNode?, _ sum: Int, _ paths: inout [[Int]], _ path: inout [Int]) {
guard let root = root else {
return
}
path.append(root.val)
if root.val == sum && root.left == nil && root.right == nil {
paths.append(path)
return
}
var pathLeft = path, pathRight = path
dfs(root.left, sum - root.val, &paths, &pathLeft)
dfs(root.right, sum - root.val, &paths, &pathRight)
}
}