Binary Tree Paths

easy

Given the root of a binary tree, return all root-to-leaf paths, each as a string with node values joined by "->". A leaf is a node with no children. Paths are returned in preorder (left before right).

The tree is given in level-order (breadth-first), using null for missing children.

Hints

DFS from the root, carrying the list of values on the current route.
When you reach a leaf, join the collected values with '->' and record the path.
Recurse left before right to list the paths in preorder.

Common doubts

Only at a leaf — a node with neither a left nor a right child; interior nodes never emit a path.
Append immutably (build a new list/string per call) or push then pop the value when backtracking, so each branch sees only its own ancestors.
Preorder — left branch before right — because we recurse (or pop) left first.

Interview follow-ups

Carry a running number (num*10 + val) down and add it at each leaf, rather than building strings.
Carry the remaining target down and record the path when it hits zero at a leaf.

Fun facts

  • This 'carry state down, snapshot at leaves' pattern powers path-sum, sum-of-numbers, and many backtracking problems.
  • The number of root-to-leaf paths equals the number of leaves in the tree.

Asked at

AmazonGoogleApple
Frequently Sometimes Occasionally
Example 1
Input: root = [1, 2, 3, null, 5]
Output: ["1->2->5", "1->3"]
Two root-to-leaf paths: 1->2->5 and 1->3.
Example 2
Input: root = [1]
Output: ["1"]
A single node is itself a root-to-leaf path.
Constraints

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

Solve this problem →