Skip to content

Commit

Permalink
Merge pull request soapyigu#162 from soapyigu/Tree
Browse files Browse the repository at this point in the history
[Tree] Add a solution to Path Sum III
  • Loading branch information
soapyigu authored Dec 14, 2016
2 parents 4410a19 + 9630379 commit 83ce280
Showing 1 changed file with 48 additions and 0 deletions.
48 changes: 48 additions & 0 deletions Tree/PathSumIII.swift
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
}
}

0 comments on commit 83ce280

Please sign in to comment.