Skip to content

Commit e546aab

Browse files
authored
feat: add swift implementation to lcof2 problem: No.050 (doocs#3065)
1 parent f711e88 commit e546aab

File tree

2 files changed

+97
-0
lines changed

2 files changed

+97
-0
lines changed

lcof2/剑指 Offer II 050. 向下的路径节点之和/README.md

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -241,6 +241,57 @@ function pathSum(root: TreeNode | null, targetSum: number): number {
241241
}
242242
```
243243

244+
#### Swift
245+
246+
```swift
247+
/* class TreeNode {
248+
* var val: Int
249+
* var left: TreeNode?
250+
* var right: TreeNode?
251+
* init() {
252+
* self.val = 0
253+
* self.left = nil
254+
* self.right = nil
255+
* }
256+
* init(_ val: Int) {
257+
* self.val = val
258+
* self.left = nil
259+
* self.right = nil
260+
* }
261+
* init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {
262+
* self.val = val
263+
* self.left = left
264+
* self.right = right
265+
* }
266+
* }
267+
*/
268+
269+
class Solution {
270+
private var cnt = [Int: Int]()
271+
private var targetSum: Int = 0
272+
273+
func pathSum(_ root: TreeNode?, _ targetSum: Int) -> Int {
274+
self.targetSum = targetSum
275+
cnt[0] = 1
276+
return dfs(root, 0)
277+
}
278+
279+
private func dfs(_ node: TreeNode?, _ s: Int) -> Int {
280+
guard let node = node else {
281+
return 0
282+
}
283+
var s = s
284+
s += node.val
285+
var ans = cnt[s - targetSum, default: 0]
286+
cnt[s, default: 0] += 1
287+
ans += dfs(node.left, s)
288+
ans += dfs(node.right, s)
289+
cnt[s]! -= 1
290+
return ans
291+
}
292+
}
293+
```
294+
244295
<!-- tabs:end -->
245296

246297
<!-- solution:end -->
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/* class TreeNode {
2+
* var val: Int
3+
* var left: TreeNode?
4+
* var right: TreeNode?
5+
* init() {
6+
* self.val = 0
7+
* self.left = nil
8+
* self.right = nil
9+
* }
10+
* init(_ val: Int) {
11+
* self.val = val
12+
* self.left = nil
13+
* self.right = nil
14+
* }
15+
* init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {
16+
* self.val = val
17+
* self.left = left
18+
* self.right = right
19+
* }
20+
* }
21+
*/
22+
23+
class Solution {
24+
private var cnt = [Int: Int]()
25+
private var targetSum: Int = 0
26+
27+
func pathSum(_ root: TreeNode?, _ targetSum: Int) -> Int {
28+
self.targetSum = targetSum
29+
cnt[0] = 1
30+
return dfs(root, 0)
31+
}
32+
33+
private func dfs(_ node: TreeNode?, _ s: Int) -> Int {
34+
guard let node = node else {
35+
return 0
36+
}
37+
var s = s
38+
s += node.val
39+
var ans = cnt[s - targetSum, default: 0]
40+
cnt[s, default: 0] += 1
41+
ans += dfs(node.left, s)
42+
ans += dfs(node.right, s)
43+
cnt[s]! -= 1
44+
return ans
45+
}
46+
}

0 commit comments

Comments
 (0)