File tree 2 files changed +83
-0
lines changed
2 files changed +83
-0
lines changed Original file line number Diff line number Diff line change @@ -381,6 +381,50 @@ public class Solution {
381
381
}
382
382
```
383
383
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
+
384
428
<!-- tabs: end -->
385
429
386
430
<!-- solution: end -->
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments