Binary Tree Paths
TreesDFS
EasyLeetCode #257
Problem Statement
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
Output: ["1→2→5", "1→3"]
Algorithm Explanation
We can solve this problem using a depth-first search (DFS) approach. We'll traverse the tree from the root, keeping track of the current path.
Algorithm Steps
- DFS Function: Create a recursive DFS function that takes a node and the current path string as arguments.
- Path String: At each node, append its value to the current path string.
- Leaf Node: If the current node is a leaf, we've found a complete path. Add the path string to our result list.
- Recursive Calls: If the node is not a leaf, make recursive calls for its left and right children, passing along the updated path string.
Start
Starting DFS from the root.
Current Path
Result
Binary Tree Paths Solution