Skip to content

Commit 41bfdfa

Browse files
authored
feat: add swift implementation to lcof problem: No.34 (doocs#2904)
1 parent 44b9bbd commit 41bfdfa

File tree

2 files changed

+83
-0
lines changed

2 files changed

+83
-0
lines changed

lcof/面试题34. 二叉树中和为某一值的路径/README.md

+44
Original file line numberDiff line numberDiff line change
@@ -381,6 +381,50 @@ public class Solution {
381381
}
382382
```
383383

384+
#### Swift
385+
386+
```swift
387+
/**
388+
* Definition for a binary tree node.
389+
* public class TreeNode {
390+
* public var val: Int
391+
* public var left: TreeNode?
392+
* public var right: TreeNode?
393+
* public init() { self.val = 0; self.left = nil; self.right = nil; }
394+
* public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; }
395+
* public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {
396+
* self.val = val
397+
* self.left = left
398+
* self.right = right
399+
* }
400+
* }
401+
*/
402+
403+
class Solution {
404+
private var t = [Int]()
405+
private var ans = [[Int]]()
406+
407+
func pathSum(_ root: TreeNode?, _ target: Int) -> [[Int]] {
408+
dfs(root, target)
409+
return ans
410+
}
411+
412+
private func dfs(_ root: TreeNode?, _ s: Int) {
413+
guard let root = root else {
414+
return
415+
}
416+
t.append(root.val)
417+
let remainingSum = s - root.val
418+
if root.left == nil && root.right == nil && remainingSum == 0 {
419+
ans.append(Array(t))
420+
}
421+
dfs(root.left, remainingSum)
422+
dfs(root.right, remainingSum)
423+
t.removeLast()
424+
}
425+
}
426+
```
427+
384428
<!-- tabs:end -->
385429

386430
<!-- solution:end -->
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* public class TreeNode {
4+
* public var val: Int
5+
* public var left: TreeNode?
6+
* public var right: TreeNode?
7+
* public init() { self.val = 0; self.left = nil; self.right = nil; }
8+
* public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; }
9+
* public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {
10+
* self.val = val
11+
* self.left = left
12+
* self.right = right
13+
* }
14+
* }
15+
*/
16+
17+
class Solution {
18+
private var t = [Int]()
19+
private var ans = [[Int]]()
20+
21+
func pathSum(_ root: TreeNode?, _ target: Int) -> [[Int]] {
22+
dfs(root, target)
23+
return ans
24+
}
25+
26+
private func dfs(_ root: TreeNode?, _ s: Int) {
27+
guard let root = root else {
28+
return
29+
}
30+
t.append(root.val)
31+
let remainingSum = s - root.val
32+
if root.left == nil && root.right == nil && remainingSum == 0 {
33+
ans.append(Array(t))
34+
}
35+
dfs(root.left, remainingSum)
36+
dfs(root.right, remainingSum)
37+
t.removeLast()
38+
}
39+
}

0 commit comments

Comments
 (0)