Answer:
def binaryTreePaths(root):
res = []
def dfs(node, path):
if not node:
return
path.append(str(node.val))
if not node.left and not node.right:
res.append('->'.join(path))
dfs(node.left, path)
dfs(node.right, path)
path.pop()
dfs(root, [])
return res
Step-by-step explanation:
To solve this problem, we can use a depth-first search (DFS) approach to traverse the binary tree and keep track of the current path. When we reach a leaf node, we add the current path to our result list.
Here's the algorithm in more detail:
Create an empty list to store the result.
Create an empty list to store the current path.
Define a helper function that takes a node and the current path as input.
In the helper function, if the node is None, return.
Add the current node's value to the current path.
If the current node is a leaf node (i.e., both its left and right children are None), append the current path to the result list.
Recursively call the helper function for the left child with the updated current path.
Recursively call the helper function for the right child with the updated current path.
Call the helper function with the root node and the empty current path list.
Return the result list.
Here's the Python code implementation: