Works locally, not on LeetCode [Python]

  • 0
    class Solution:
    stack = []
    sol = []
    # @param {TreeNode} root
    # @return {string[]}
    def binaryTreePaths(self, root):
        if root == None:
            return self.sol
        if root.right == None and root.left == None:
            s = ""
            for element in self.stack:
                s+="%d->" % (element)
        return self.sol

    This code fails on LeetCode in this way (input is [1,2]):

    Expected ["1->2"], got ["1", "1->2"]

    On my computer the solution is correct. Any idea?

  • 0

    Basically, the judger runs your code with all test cases in the same process, so you have to reset the stack and sol variables in your function. Or just avoid class static variables if possible.

    Please read the FAQ, especially the question "Why does my code produce a different output compared to my local environment?" for more details.

  • 0

    I wrote a small wrapper and initialised stack and sol every time the test is started. Now it works, thanks for the clarification

Log in to reply

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