My Swift Solution


  • 0
    J
    func hasPathSum(root: TreeNode?, _ sum: Int) -> Bool {
            guard let rootNode = root else {
                return false
            }
    
            if rootNode.left == nil && rootNode.right == nil {
                return sum - rootNode.val == 0
            }
    
            return self.hasPathSum(rootNode.left, sum - rootNode.val)
                || self.hasPathSum(rootNode.right, sum - rootNode.val)
        }

  • 0
    C

    func hasPathSum(root: TreeNode?, _ sum: Int) -> Bool {

        if root == nil {
            return false
        }
        if sum == root!.val && root?.left == nil && root?.right == nil {  // 一定是叶子节点
            return true
        }
        // 分治算法,分解成小的问题去解决
        return hasPathSum(root?.left, sum - root!.val) || hasPathSum(root?.right, sum - root!.val)
    

    }


Log in to reply
 

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