I have some code in Python that is supposed to return all root to leaf paths in a binary tree in the form of a list (Ex. ["1->2->5", "1->3"] ). The original question is from leetcode.
I need help figuring out what is wrong with my code and/or alternative solutions (in Python, preferably). For the example I gave above, my code returns null while it should in fact print the list I gave. I would also appreciate insight as how you approach this problem when you first see the question.
Here is my code:
def binaryTreePaths(self, root):
list1 = []
if (root == None):
return []
if (root.left == None and root.right == None):
return list1.append(str(root.val) + "->")
if (root.left != None):
list1.append(self.binaryTreePaths(root.left))
if (root.right != None):
list1.append(self.binaryTreePaths(root.right))