Skip to content

Commit 5563d6e

Browse files
committed
[Tree] Optimize syntax for Path Sum II
1 parent 593a571 commit 5563d6e

File tree

1 file changed

+18
-19
lines changed

1 file changed

+18
-19
lines changed

Tree/PathSumII.swift

Lines changed: 18 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -20,30 +20,29 @@
2020
*/
2121

2222
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
23+
func pathSum(_ root: TreeNode?, _ sum: Int) -> [[Int]] {
24+
var paths = [[Int]](), path = [Int]()
25+
26+
dfs(root, sum, &paths, &path)
27+
28+
return paths
3029
}
31-
32-
private func _dfs(inout res: [[Int]], inout _ list:[Int], _ root: TreeNode?, _ sum: Int) {
33-
guard let root = root else {
30+
31+
fileprivate func dfs(_ root: TreeNode?, _ sum: Int, _ paths: inout [[Int]], _ path: inout [Int]) {
32+
guard let root = root else {
3433
return
3534
}
3635

37-
if root.left == nil && root.right == nil && root.val == sum {
38-
list.append(root.val)
39-
res.append(list)
36+
path.append(root.val)
37+
38+
if root.val == sum && root.left == nil && root.right == nil {
39+
paths.append(path)
4040
return
4141
}
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)
42+
43+
var pathLeft = path, pathRight = path
44+
45+
dfs(root.left, sum - root.val, &paths, &pathLeft)
46+
dfs(root.right, sum - root.val, &paths, &pathRight)
4847
}
4948
}

0 commit comments

Comments
 (0)