Python 不同的';运行';和';提交';结果(Leetcode#257个二叉树路径)

Python 不同的';运行';和';提交';结果(Leetcode#257个二叉树路径),python,Python,我已经写了一个leetcode问题的基本解决方案 对于失败的测试用例([]),“运行代码”生成正确的结果([]);但是,“提交”会产生不正确的结果([“1->2->5”,“1->3”]) “提交”会产生与原始测试用例相同的输出。。。然而,我不确定为什么会发生这种情况,因为输入明显不同 任何提示,谢谢 # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left

我已经写了一个leetcode问题的基本解决方案

对于失败的测试用例([]),“运行代码”生成正确的结果([]);但是,“提交”会产生不正确的结果([“1->2->5”,“1->3”])

“提交”会产生与原始测试用例相同的输出。。。然而,我不确定为什么会发生这种情况,因为输入明显不同

任何提示,谢谢

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution(object):
    global paths
    paths = [ ]

    def binaryTreePaths(self, root):
        """
        :type root: TreeNode
        :rtype: List[str]
        """
        
        if (root):
            curr_path = str(root.val)
            self.binaryTreePathsHelper(root.left, curr_path)
            self.binaryTreePathsHelper(root.right, curr_path)
        
        return paths
    
    def binaryTreePathsHelper(self, node, path):
        
        # so the leaf (base case) has no children
        # base case
        if (node):
            path = path + "->" + str(node.val)
            
            if (not node.left and not node.right):
                paths.append(path)
            else:
                # append curr_node
                # & recursively call
                self.binaryTreePathsHelper(node.left, path)
                self.binaryTreePathsHelper(node.right, path)

路径
在解决方案类级别定义为全局路径。因此,如果重用了解决方案对象,或者创建了多个解决方案对象,则会将其初始化为空列表,而不会重新初始化。因此,一旦生成一个非空结果,它将挂在
路径中,污染以后的结果。最好将
路径
设为实例属性,并在
二进制树路径
方法中对其进行初始化