Swift solution


  • 0
    A
    class Solution {
        func hasPathSum(_ root: TreeNode?, _ sum: Int) -> Boo l{
            guard let root = root else { return false }
            
            
            if let left = root.left, let right = root.right {
                // min between left and right
                return hasPathSum(left, sum - root.val) || hasPathSum(right, sum - root.val)
            } else if let left = root.left {
                // left path
                return hasPathSum(left, sum - root.val)
            } else if let right = root.right {
                return hasPathSum(right, sum - root.val)
            } else {
                // leaf
                return sum - root.val == 0
            }
        }
    }
    

Log in to reply
 

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