forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request soapyigu#162 from soapyigu/Tree
[Tree] Add a solution to Path Sum III
- Loading branch information
Showing
1 changed file
with
48 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,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 | ||
} | ||
} |