Firstly, I am a newbie in Python. I have the following class and a method names inorderTraversal() inside it:
class Solution(object):
mylist=[]
def inorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
I am supposed to populate this method for the inorder traversal of a Binary Tree. Here is my code:
def inorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if root:
if(root.left):
self.inorderTraversal(root.left)
#print(root.val)
Solution().mylist.append(root.val)
if(root.right):
#print("Root.right contains:",root.right.val)
self.inorderTraversal(root.right)
return Solution().mylist
The problem is, when I run the code with one example it shows the desired output. Again when I run the code, the output just gets concatenated to the output of the first example. Like,
for [1] as the input, the output should be [1] but for the second test case [], output still remains [1] because it's just concatenating the result with the previous.
I understand that the problem might be as I am trying to create new instances of the class Solution with the statement Solution(), the output list is getting concatenated with the previous output. But why is it happening? Because as per the statement mylist=[] where mylist is an instance variable, every time a new instance of the class is created the mylist gets initialized to []. Then how can mylist stiull hold the output of the previous example?
Please assist. Thanks in advance.