Magicsheet logo

Binary Tree Paths

Easy
49%
Updated 6/1/2025

Binary Tree Paths

What is this problem about?

The Binary Tree Paths coding problem asks you to find all possible paths from the root of a binary tree down to every leaf node. You need to return these paths as a list of strings, usually formatted like "1->2->5". This problem is an excellent introduction to "path-finding" in trees and requires you to keep track of the current path as you explore deeper into the structure.

Why is this asked in interviews?

Companies like Meta, Amazon, and Microsoft use this to test a candidate's ability to perform a complete traversal and collect state along the way. It’s a foundational Backtracking interview pattern. It tests whether you understand how to pass strings or lists through recursive calls and how to identify when you've reached a "terminal" state (a leaf node).

Algorithmic pattern used

This problem primarily uses Depth-First Search (DFS) or Backtracking. As you move from a parent to a child, you append the current node's value to a "running" path string. When you reach a node that has neither a left nor a right child, you know you've completed a path and can add the final string to your results list.

Example explanation

Consider the following tree: 1 / 2 3

5
  1. Start at 1. Current path: "1".
  2. Go left to 2. Current path: "1->2".
  3. Go right from 2 to 5. 5 is a leaf! Result: ["1->2->5"].
  4. Backtrack to 1, then go right to 3. 3 is a leaf! Result: ["1->2->5", "1->3"]. Final output: ["1->2->5", "1->3"].

Common mistakes candidates make

One common mistake is adding the "->" separator incorrectly—either putting one at the very end of the string or forgetting it between nodes. Another mistake is not handling the base case of an empty tree. In some languages, candidates also struggle with string immutability, creating many unnecessary string objects instead of using a StringBuilder or a list that they join at the end.

Interview preparation tip

When a problem asks for "all paths," think DFS. When it asks for "shortest path," think BFS. For this problem, practice using a list to store the current nodes and only convert it to a string when you hit a leaf. This is generally more efficient than constant string concatenation.

Similar Questions