Swift solution - DFS


  • 0
    class Solution {
        func pathSum(_ root: TreeNode?, _ sum: Int) -> Int {
            guard let root = root else {
                return 0
            }
            
            return findPath(root, sum) + pathSum(root.left, sum) + pathSum(root.right, sum)
        }
        
        func findPath(_ root: TreeNode?, _ sum: Int) -> Int {
            guard let root = root else {
                return 0
            }
            
            var result = 0
            
            if sum == root.val {
                result += 1
            }
            result += findPath(root.left, sum - root.val)
            result += findPath(root.right, sum - root.val)
            
            return result
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.