Why does this Python solution produce different answers between "Run Code" and "Submit Solution"?


  • 0
    D
    def rightSideView(self, root, ans=[], depth=0):
        if not root:
            return []
        if len(ans) == depth:
            ans.append(root.val)
        self.rightSideView(root.right, ans, depth+1)
        self.rightSideView(root.left, ans, depth+1)
        return ans
    

    It's an implementation of the number 1 voted Java solution. I cannot pass the test case [1,null,3] because the code outputs [1,2], but when I use "Run Code" (and in my own environment), I get the correct [1,3]. Why is this?


  • 0

    Please read the FAQ regarding this issue:
    https://leetcode.com/faq/#different-output

    Secondly, you have to realize that by assigning a default value to a mutable type (ie, a list) will result that same list is being reused for each test case, which is probably not what you expected:
    http://effbot.org/zone/default-values.htm

    Note: This is a common pitfall for Python beginners.


Log in to reply
 

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