Swift solution - recursive


  • 0
    class Solution {
        func pathSum(_ root: TreeNode?, _ sum: Int) -> [[Int]] {
            var paths = [[Int]]()
            var path = [Int]()
            
            helper(root, sum, &path, &paths)
            
            return paths
        }
        
        private func helper(_ root: TreeNode?, _ sum: Int, _ path: inout [Int], _ paths: inout [[Int]]) {
            guard let root = root else {
                return
            }
            
            path.append(root.val)
            if root.left == nil && root.right == nil && sum == root.val {
                paths.append(path)
            } else {
                helper(root.left, sum - root.val, &path, &paths)
                helper(root.right, sum - root.val, &path, &paths)
            }
            path.removeLast()
        }
    }
    

Log in to reply
 

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