I am trying to solve the coding question of "Given a binary tree, return all root-to-leaf paths."
Input:
1
/ \
2 3
\
5
Output: ["1->2->5", "1->3"]
I have seen one solution
class Solution:
def binaryTreePaths(self, root: TreeNode) -> List[str]:
allPath = []
if root is None:
return []
self.find_all_paths_recursive(root, [], allPath)
return allPath
def find_all_paths_recursive(self, currNode, currPath, allPath):
if currNode is None:
return
currPath.append(currNode.val)
if currNode.left is None and currNode.right is None:
currOut = '->'.join([str(x) for x in list(currPath)])
allPath.append(currOut)
# traverse left sub tree
self.find_all_paths_recursive(currNode.left, currPath, allPath)
# traverse right sub tree
self.find_all_paths_recursive(currNode.right, currPath, allPath)
del currPath[-1]
Running the above code gave me the answer of ["1->2->5", "1->3"], whcih is correct.
I was thinking by changing the code block under if currNode.left is None and currNode.right is None:
to
if currNode.left is None and currNode.right is None:
#currOut = '->'.join([str(x) for x in list(currPath)])
#allPath.append(currOut)
allPath.append(currPath)
should gave me the results [[1,2,5], [1,3]]. However, this change returned me the results [[],[]]. I wonder why this doesn't work?