Binary Tree Paths
The key idea
Walk the tree depth-first, carrying the path of values seen so far. A node with no children is a leaf, so join the accumulated values with
-> and record that one path. The recursion's own call stack tracks the current path for you.Problem
Given the root of a binary tree, return all the root-to-leaf paths in any order.
A leaf is a node with no children. Each path is the sequence of node values from root down to a leaf, written as the values joined by -> (for example, 1->2->5).
Constraints
- The number of nodes in the tree is in the range
[1, 100]. -100 <= Node.val <= 100
Examples
Input: root = [1,2,3,null,5]
Output: ["1->2->5","1->3"]
Input: root = [1]
Output: ["1"]
Complexity
Time: O(n) Space: O(n)
See the full solution
- ✓Full worked approach
- ✓Reference code in 5 languages
- ✓Problem-solving tips
- ✓Step-by-step animated visualization
More Tree / Recursion problems
- Balanced Binary TreeEASY
- Binary Tree CamerasHARD
- Binary Tree Inorder TraversalEASY
- Binary Tree Maximum Path SumHARD
- Binary Tree Postorder TraversalEASY
- Binary Tree Preorder TraversalEASY
- House Robber IIIMEDIUM
- Construct Binary Tree from Inorder and Postorder TraversalMEDIUM
- Construct Binary Tree from Preorder and Inorder TraversalMEDIUM
- Convert BST to Greater TreeMEDIUM
- Count Complete Tree NodesEASY
- Count Good Nodes in Binary TreeMEDIUM