Skip to content

Commit 5489a4e

Browse files
author
Yi Gu
committed
[Tree] add solution to path sum ii
1 parent 3c3d8b3 commit 5489a4e

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

Tree/PathSumII.swift

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
/**
2+
* Question Link: https://leetcode.com/problems/path-sum-ii/
3+
* Primary idea: recursion
4+
*
5+
* 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.
6+
*
7+
* Time Complexity: O(n), Space Complexity: O(1)
8+
*
9+
* Definition for a binary tree node.
10+
* public class TreeNode {
11+
* public var val: Int
12+
* public var left: TreeNode?
13+
* public var right: TreeNode?
14+
* public init(_ val: Int) {
15+
* self.val = val
16+
* self.left = nil
17+
* self.right = nil
18+
* }
19+
* }
20+
*/
21+
22+
class PathSumII {
23+
func pathSum(root: TreeNode?, _ sum: Int) -> [[Int]] {
24+
var res = [[Int]]()
25+
var list = [Int]()
26+
27+
_dfs(&res, &list, root, sum)
28+
29+
return res
30+
}
31+
32+
private func _dfs(inout res: [[Int]], inout _ list:[Int], _ root: TreeNode?, _ sum: Int) {
33+
if root == nil {
34+
return
35+
}
36+
if root!.left == nil && root!.right == nil && root!.val == sum {
37+
list.append(root!.val)
38+
let dupList = list
39+
res.append(dupList)
40+
return
41+
}
42+
43+
list.append(root!.val)
44+
var dupListLeft = list
45+
var dupListRight = list
46+
_dfs(&res, &dupListLeft, root!.left, sum - root!.val)
47+
_dfs(&res, &dupListRight, root!.right, sum - root!.val)
48+
}
49+
}

0 commit comments

Comments
 (0)