Binary Tree Paths (LeetCode 257): Solution and Explanation

Easy
String
Backtracking
Tree
Depth First Search
Binary Tree

Given a binary tree, list every path from the root down to a leaf. Each path is returned as a string of node values joined by arrows, such as 1->2->5, and the paths can come back in any order.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

Any question that asks for every root-to-leaf path is a depth-first search question. DFS naturally follows one path from the root all the way down before backing up and trying the next branch, so at any moment the current call stack describes exactly one path.

All you need is a way to remember that path as you go. Since the answer is a string anyway, the reference solution carries a string down the recursion. Each call appends its own value to the string it received. If the node is a leaf, the string is a finished answer. If not, the call adds the arrow separator and hands the string to both children.

Because Python strings are immutable, path += str(root.val) creates a new string local to that call. That means you never have to undo anything when the recursion returns: the parent's path is untouched by whatever the children did. This is backtracking without an explicit pop, at the cost of building a new string at each node.

Adding the arrow only for non-leaf nodes is what keeps the output clean. A leaf ends its path with its own value and no trailing separator, so there is no need to trim anything afterward.

Approach: DFS with string accumulation

  1. If the root is None, return an empty list.
  2. Create paths and define dfs(root, path), which returns immediately on a None node.
  3. Append the node's value to the path with path += str(root.val).
  4. If the node is a leaf, add path to paths, since it is a complete root-to-leaf string.
  5. Otherwise append the -> separator and call dfs on the left child and then the right child with the extended string.
  6. Call dfs(root, "") and return paths.

Step-by-step example

root = [1,2,3,null,5]
  1. At node 1 the path becomes 1. It has children, so the path becomes 1-> and the search goes left.
  2. At node 2 the path becomes 1->2. Node 2 has a right child, so it is not a leaf, and the path becomes 1->2->.
  3. The left child of 2 is None, so that call returns at once. The right child is 5.
  4. At node 5 the path becomes 1->2->5. It is a leaf, so it is added to paths.
  5. Back at node 1, its own local path is still 1->. At node 3 it becomes 1->3, which is a leaf, so it is added.
  6. The result is [1->2->5, 1->3].

Code: Python, Java, C++

1class Solution:
2    def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
3        if not root:
4            return []
5            
6        paths = []
7        
8        def dfs(root, path):
9            if not root:
10                return
11            
12            path += str(root.val)
13            
14            if not root.left and not root.right:
15                paths.append(path)
16            else:
17                path += "->"
18                dfs(root.left, path)
19                dfs(root.right, path)
20                
21        dfs(root, "")
22        return paths

Time and space complexity

Time

O(n²)

Every node is visited once, but building the string at a node copies a path of length up to the height h. That gives O(n × h), which is O(n²) for a skewed tree and O(n log n) for a balanced one.

Space

O(h²)

The recursion is h calls deep and each frame holds its own string of length up to O(h). The output is not counted, though in the worst case it also holds O(n²) characters.

Other approaches

Backtracking with a list of values (time O(n × h), space O(h))

Keep one shared list of node values, append on the way down and pop on the way back up, and only join it into a string with arrows when you reach a leaf. This avoids rebuilding strings at internal nodes, so the extra work is only paid for real answers.

Iterative DFS with a stack (time O(n²), space O(n²))

Push pairs of (node, path string) onto a stack, pop them one at a time, and push children with the extended string. It produces the same answers without recursion, which helps on very deep trees.

Common mistakes

  • Adding the arrow before checking for a leaf, which leaves a trailing -> on every path.
  • Recording a path at any node with a missing child. A node with one child is not a leaf, and doing so produces paths that stop early.
  • Using a shared mutable list without popping after the recursive calls, so values from one branch leak into the next path.
  • Forgetting to convert values with str(), which raises a type error when concatenating an integer to a string.

Frequently asked questions

Why don't we need to undo the path in this solution?

Strings in Python are immutable, so path += str(root.val) makes a new string for that call only. When the call returns, the parent still has its original string, so there is nothing to remove.

What is the time complexity of Binary Tree Paths?

Visiting nodes is O(n), but copying the path string at each node costs up to O(h). Together that is O(n × h), which is O(n²) in the worst case.

Can Binary Tree Paths be solved with BFS?

Yes. Keep a queue of (node, path so far) pairs and add a path to the answer whenever you pop a leaf. The paths come out ordered by depth rather than left to right, which is fine because any order is accepted.