A question about Python solution


  • 0
    2

    I wrote the code like below can pass the test:

    class Solution(object):
        def pathSum(self, root, sum):
            def path(root, sum, p):
                if root is None:
                    return 0
                s = 0
                pt = []
                pt.extend(p)
                pt.append(0)
                for i in range(len(pt)):   
                    pt[i] += root.val
                    if pt[i] == sum:
                        s += 1
                return path(root.left, sum, pt) + path(root.right, sum, pt) + s
            return path(root, sum, [])
    

    But if I change the code to that, the answer is wrong:

    class Solution(object):
        def pathSum(self, root, sum):
            def path(root, sum, pt):
                if root is None:
                    return 0
                s = 0
                pt.append(0)
                for i in range(len(pt)):
                    pt[i] += root.val
                    if pt[i] == sum:
                        s += 1
                return path(root.left, sum, pt) + path(root.right, sum, pt) + s
            return path(root, sum, [])
    

    Why python updates the old array in a new method?
    It's really confused me. Is there anyone can explain the reason for me?
    Thanks!


Log in to reply
 

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