Community Problem

Binary Tree Paths

Difficulty: Easy

Return every root-to-leaf path in a binary tree as a list of arrow-joined strings.

Binary Tree Paths

Return every root-to-leaf path in a binary tree as a list of arrow-joined strings.

EASY
Free
trees
binary-tree
dfs
recursion

By CodeSnatch

January 29, 2026

·

Updated May 20, 2026

813 views

14

4.5 (10)

Onboarding a junior on tree recursion last quarter, this is the problem I leaned on after Invert Binary Tree clicked. The official catalog has DFS-on-tree problems, but it skipped the cleanest one for teaching the path-accumulator pattern: how do you carry a partial answer down the recursion stack without mutating it on the way back up? That is the entire lesson here.

Binary Tree Paths

Given the root of a binary tree, return all root-to-leaf paths in any order. Each path is rendered as a string of node values joined by "->". A leaf is a node with no children.

Examples

Example 1:

  • Input: root = [1, 2, 3, null, 5]
  • Output: ["1->2->5", "1->3"]
  • Explanation: Two leaves, two paths. The leaf at value 5 traces back through 2 and 1; the leaf at value 3 traces directly through 1.

Example 2:

  • Input: root = [1]
  • Output: ["1"]
  • Explanation: A single-node tree is itself a leaf, so the only path is the one-element string "1".

Example 3:

  • Input: root = [1, 2]
  • Output: ["1->2"]
  • Explanation: A degenerate left chain has one leaf and therefore one path.

Example 4:

  • Input: root = [10, 20, 30, 40, 50, 60, 70]
  • Output: ["10->20->40", "10->20->50", "10->30->60", "10->30->70"]
  • Explanation: A perfect tree of depth 3 produces exactly four root-to-leaf paths.

Constraints

  • The number of nodes in the tree is in the range [1, 100].
  • -100 <= Node.val <= 100.

Follow-up

Can you do it iteratively with an explicit stack of (node, pathSoFar) pairs? When does that pay off versus the recursive version?

Solution

Hints

0/4
Hint 1
Hint 2
Hint 3
Hint 4
All Problems