Clean and simple Swift recursive solution


  • 0
    A
    class Solution {
        func pathSum(_ root: TreeNode?, _ sum: Int) -> [[Int]] {
            guard root != nil else { return [] }
            let r = root!
            
            if r.val == sum && r.left == nil && r.right == nil {
                return [[sum]]
            }
            
            let lps = pathSum(r.left, sum - r.val)
            let rps = pathSum(r.right, sum - r.val)
            
            return (lps + rps).map { [r.val] + $0 }
        }
    }
    

Log in to reply
 

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