Skip to main content

All Root-to-Leaf Path Enumerator

medium
TreeDepth First SearchBinary TreeBacktrackingDfs RecursiveBacktracking Combinations
Asked atAmazonGoogleUberBloomberg

Problem Description

Given the root of a binary tree, collect **all paths from the root to every leaf node**. Each path should be represented as a list of node values in traversal order (from root to leaf).

A **leaf** is a node that has no children. Return all paths in any order.

**Example 1:**
```
4
/ \
2 7
/ \ \
1 3 9
```
Input: root = [4,2,7,1,3,null,9]
Output: [[4,2,1],[4,2,3],[4,7,9]]

**Example 2:**
```
8
/
5
```
Input: root = [8,5]
Output: [[8,5]]
Explanation: Node 5 is the only leaf; the single path is root → 5.

Constraints

  • The number of nodes is in the range [1, 1000].
  • Node values are integers in the range [-200, 200].
  • The root is always non-null.

Follow-up

Can you also return the sum of all root-to-leaf path values (treating each path as a number formed by concatenating its digits)?

Hints

Try the problem first. If you get stuck, you can reveal hints one at a time.

Solution

Leaderboard

No entries yet for python.

Be the first — submit an accepted solution.