Readable Recursive Python Solution


  • 0
    P

    class Solution(object):

    def pathSum(self, root, sum):
        """
        :type root: TreeNode
        :type sum: int
        :rtype: int
        """
        if not root:
            return 0
        count = self.pathRootSum(root, sum) + self.pathSum(root.left, sum) + self.pathSum(root.right, sum)
        return count     
    def pathRootSum(self, root, sum):
        """
        :type root: TreeNode
        :type sum: int
        :rtype: int
        """
        if not root:
            return 0
        if root.val==sum:
            return 1 + self.pathRootSum(root.left, sum-root.val) + self.pathRootSum(root.right, sum-root.val)
        return self.pathRootSum(root.left, sum-root.val) + self.pathRootSum(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.