Another simple python solution


  • 3
    R
    class Solution(object):
        def pathSum(self, root, sum):
            """
            :type root: TreeNode
            :type sum: int
            :rtype: int
            """
            if not root: return 0
            return (1 if root.val == sum else 0) +\
                   self.helper(root.left, sum-root.val) +\
                   self.helper(root.right, sum-root.val) +\
                   self.pathSum(root.left, sum) +\
                   self.pathSum(root.right, sum)
            
        def helper(self, root, sum):
            if not root: return 0
            return (1 if root.val == sum else 0) +\
                   self.helper(root.left, sum-root.val) +\
                   self.helper(root.right, sum-root.val)
    

  • 0

    Looks great!


  • -1

    @ravipp
    what does "+" mean?


  • -1

    @sharing-account what does "+" mean?


  • 2

    Could change "(1 if root.val == sum else 0) + self.helper(root.left, sum-root.val) + self.helper(root.right, sum-root.val)" in the "pathSum" into "helper(root, sum)" to save some syntax.

    class Solution(object):
        def pathSum(self, root, sum):
            """
            :type root: TreeNode
            :type sum: int
            :rtype: int
            """
            if not root: return 0
            return self.helper(root, sum) +\ 
                   self.pathSum(root.left, sum) +\
                   self.pathSum(root.right, sum)
            
        def helper(self, root, sum):
            if not root: return 0
            return (1 if root.val == sum else 0) +\
                   self.helper(root.left, sum-root.val) +\
                   self.helper(root.right, sum-root.val)
    

  • 0

    @sharing-account
    In each case, once root.val == sum is True, which means we find one more solution, then we give an 1. Thus "+" means adding all possible solution together to get the final answer.


Log in to reply
 

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