Given the root
of a binary tree, return all root-to-leaf paths in any order.
A leaf is a node with no children.
Example 1:
Input: root = [1,2,3,null,5] Output: ["1->2->5","1->3"]
Example 2:
Input: root = [1] Output: ["1"]
Constraints:
[1, 100]
.-100 <= Node.val <= 100
This problem asks to find all root-to-leaf paths in a binary tree. A root-to-leaf path is a sequence of nodes from the root node to a leaf node (a node with no children). The solution uses Depth-First Search (DFS) with backtracking to efficiently explore all paths.
The core idea is to recursively traverse the tree. For each node:
class Solution:
def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
ans = [] # Result list to store paths
t = [] # Temporary list to build current path
def dfs(node):
if node is None:
return
t.append(str(node.val)) # Append node value (converted to string)
if node.left is None and node.right is None: # Leaf node reached
ans.append("->".join(t)) # Add path to result
else:
dfs(node.left) # Explore left subtree
dfs(node.right) # Explore right subtree
t.pop() # Backtrack: Remove last element before returning
dfs(root)
return ans
The other language examples follow a similar structure:
dfs
) to perform the Depth-First Search.t
) to store the path as it is being built.ans
) only when a leaf node is reached.The time complexity is O(N), where N is the number of nodes in the binary tree. This is because each node is visited and processed exactly once during the DFS traversal.
The space complexity can be:
The overall space complexity is dominated by the recursion stack and the storage of the results, making it O(N) in the worst case.