Python Solution - output is not same as OJ


  • 0
    E

    I have my python solution like this:

    from copy import copy
    
    # Definition for a binary tree node.
    # class TreeNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution(object):
        global paths
        paths = []
        def pathSum(self, root, num):
            """
            :type root: TreeNode
            :type num: int
            :rtype: List[List[int]]
            """
            routes = []
            self.traverseall(root)
            # print paths
            for path in paths:
                # print path
                if num == sum(path):
                    routes.append(path)
            return routes
    
    
        def traverseall(self,node, path=None):
            # path = path or []
            if path is None:
                path = []
    
            if node is None:
                return
    
            path.append(node.val)
    
            if node.left is None and node.right is None: # is leaf
                # print path
                paths.append(path)
            else:
                if node.left is not None:
                    self.traverseall(node.left, copy(path)) # MUST USE COPY
                if node.right is not None:
                    self.traverseall(node.right, copy(path)) # MUST USE COPY
    

    with the test case of

    [1,2]
    1
    

    I got output [] which is correct.

    But as I send my answer by pressing Submit Solution button.
    The system just tole me I got the wrong answer with the same test case of [1,2] and 1 which is mention above.
    The system says that I got the output [[1],[1]], which is expected to get [].

    How can I get a [[1],[1]] while submitting my answer but get a [] while just running the code online?


  • 0

    It's because you explicitly tried hard (and succeeded) to keep paths the same list object for all test cases (don't know why you want that) and forgot to reset it between test cases.


  • 0
    E

    @StefanPochmann Thank you. It was a dumb question. I ended up clear the paths list by using del paths[:] before returning routes list. However, the way I solved this problem is logically weird, indeed. I will think about this further and hope possibly come up with a nicer solution by myself. Thank you again.


Log in to reply
 

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