-
Notifications
You must be signed in to change notification settings - Fork 889
/
PathSumIII.swift
48 lines (40 loc) · 1.18 KB
/
PathSumIII.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/**
* Question Link: https://leetcode.com/problems/path-sum-iii/
* Primary idea: Get path number of every node as root while iterating the tree
* Time Complexity: O(n^2), Space Complexity: O(1)
*
* Definition for a binary tree node.
* public class TreeNode {
* public var val: Int
* public var left: TreeNode?
* public var right: TreeNode?
* public init(_ val: Int) {
* self.val = val
* self.left = nil
* self.right = nil
* }
* }
*/
class PathSumIII {
func pathSum(_ root: TreeNode?, _ sum: Int) -> Int {
guard let root = root else {
return 0
}
var res = totalPaths(root, sum)
let left = pathSum(root.left, sum)
let right = pathSum(root.right, sum)
return res + left + right
}
func totalPaths(_ root: TreeNode?, _ sum: Int) -> Int {
guard let root = root else {
return 0
}
var res = 0
if sum == root.val {
res += 1
}
res += totalPaths(root.left, sum - root.val)
res += totalPaths(root.right, sum - root.val)
return res
}
}