I am trying to write a program to find leaf value sequences in python (https://leetcode.com/problems/leaf-similar-trees/description/?envType=study-plan-v2&envId=leetcode-75)
Here is my code
def leaves(root,ans) :
if(root.left == None and root.right == None) :
ans.append(root.val)
return(ans)
elif (root.left == None ):
ans = ans + leaves(root.right,ans)
return(ans)
elif (root.right == None) :
ans = ans + leaves(root.left,ans)
return(ans)
else :
ans = ans + leaves(root.left,ans) + leaves(root.right,ans)
return(ans)
For the case [1,2,3]
in the 2nd example the function leaves([1,2,3],[]) should return [2,3] but instead returns [2,2,2,3]
. I assume that the error is because the variable ans is a global variable. My understanding is that it should be a local variable each time when passed to a function. Please explain if my understanding is correct
Also what corrections do I need to make to the code