What's wrong with my code?


  • 0
    H
    class Solution:
    # @param root, a tree node
    # @return a list of integers
    result=[]
    def preorderTraversal(self, root):
        if root:
            self.result.append(root.val)
            self.preorderTraversal(root.left)
            self.preorderTraversal(root.right)
        return self.result

  • 3

    You are defining result as a class' static variable. As the judge runs your code for all test cases in one go, the static variable will be reused for the next test case and so on. Unless you clear the variable each time the function is called, the result will be wrong.

    A better alternative is to define result as an instance variable, where you initialize it in the constructor as shown below.

    class Solution:
    # @param root, a tree node
    # @return a list of integers
        def __init__(self):
            self.result=[]
            
        def preorderTraversal(self, root):
            if root:
                self.result.append(root.val)
                self.preorderTraversal(root.left)
                self.preorderTraversal(root.right)
            return self.result

  • 0
    H

    You are right, thanks!


Log in to reply
 

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