Intuition
Use backtracking to remember path and construct the result
- Initialize an empty list to store the paths.
- Define a helper function that takes the current node and the current path as parameters.
- If the current node is null, return.
- Append the current node's value to the current path.
- If the current node is a leaf node, add the current path to the list of paths.
- Recursively call the helper function on the left and right children of the current node.
- Remove the last element from the current path.
Optimal Solution
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
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))
else:
dfs(node.left, path)
dfs(node.right,path)
path.pop()
dfs(root, [])
return res
Time Complexity
Time Complexity O(N)
Space Complexity O(H)