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
What's wrong with my code?

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