Problem Description
Given the root of a binary tree, return all root-to-leaf paths as strings where each node is separated by "->". A leaf is defined as a node with no children.
Key Insights
- Use a Depth-First Search (DFS) or backtracking approach to explore all paths from the root to leaves.
- Build the path as you traverse the tree.
- Once a leaf node is reached, append the constructed path to the result list.
- The problem requires returning all paths in any order.
Space and Time Complexity
Time Complexity: O(N), where N is the number of nodes in the tree, since every node is visited once. Space Complexity: O(H), where H is the height of the tree, which is the space used on the recursion stack. In the worst case (skewed tree), H can be O(N).
Solution
We perform a DFS traversal starting from the root. At each node, we append the node's value to the current path. If the current node is a leaf (i.e. it does not have left or right children), we add the current path (constructed as a string separated by "->") to the result. Otherwise, we recursively process the left and right children. The recursion naturally handles backtracking since the current path is passed (or extended) at each recursive call.