15% off all plans & roadmaps Use code

See plans

Binary Tree Paths

Updated

TL;DR: Return every root-to-leaf path in a binary tree as an arrow-joined string. Walk the tree once with DFS, keep the current path in one shared list, and record a copy of it at each leaf.

Problem

You are given the root of a binary tree. Return every path that runs from the root down to a leaf. You may return the paths in any order.

A leaf is a node that has no children.

Example 1

Input: root = [1,2,3,null,5]
Output: ["1->2->5","1->3"]

Example 2

Input: root = [1]
Output: ["1"]

Constraints

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

Constraints that matter

  • Up to 100 nodes means an O(N^2) search over the tree is affordable, but a faster idea is still worth having for interviews.
  • The tree can be skewed, so the depth can reach 100. Recursion of that depth is safe in every language here.
  • Values range from -100 to 100 and can be negative or repeated. Never use the value to identify a node, only the node reference.
  • Every path must end at a leaf. A node with one child is not a leaf, so it must not produce its own answer.

View on LeetCode

Hints

Hint 1

The answer is a set of root-to-leaf sequences, so the problem asks for a traversal that remembers where it has been.

Hint 2

The naive solution first gathers every leaf.

Solution

Intuition

The answer is a set of root-to-leaf sequences, so the problem asks for a traversal that remembers where it has been. Any time you need to report all paths from a root, think of the pattern of recursive preorder traversal. You visit the current node first, add it to the path, then recurse into the children.

It is like a hiker with one notepad who writes each junction going down a forest trail and erases it going back up. The notepad is the shared path list, and each recursive call is one step along the trail.

The key observation is that a path to any node is the path to its parent plus that node. You never need to rebuild the path from scratch. If you pass the prefix down the recursion, each call only adds one value.

The trick is to undo that addition when the call returns. One shared list works if you pop the value after exploring both children. That is the backtracking step, and it keeps the list correct for the sibling subtree.

Watch the pattern animation

Worked example

Input: root = [1, null, 2, null, 3]
Output: ["1->2->3"]
Explanation: The tree is a single chain. Node 1 has only a right child 2, and node 2 has only a right child 3. Node 3 is the only leaf, so the answer holds one path: 1, then 2, then 3.

Approach 1: Brute force: search from the root for each leaf

The naive solution first gathers every leaf. For each leaf, it then searches the whole tree from the root to find the path that ends there. The search does not remember anything from earlier searches. Each leaf triggers a fresh scan of the tree, so the same nodes are visited again and again.

The insight that fixes this is that one traversal already knows the path to every leaf. The optimal approach keeps that path as it goes and never searches twice.

Steps

  1. Walk the tree once and collect every node that has no children.
  2. For each collected leaf, call a search that starts at the root.
  3. In the search, push the current node value onto a list before checking whether the node is the target.
  4. If the target is found, return true and keep the list. If not, pop the value and try the other child.
  5. Join the list with "->" and add the string to the result.

Dry run

Take the example tree 1 -> 2 -> 3 along right children. The collect step finds one leaf, node 3.

StepNode visitedList after pushFound target?
11[1]no, go right
22[1, 2]no, go right
33[1, 2, 3]yes, stop

Joining [1, 2, 3] with "->" gives "1->2->3", which matches the expected output.

Complexity

TimeO(N^2) in the worst case
SpaceO(N)

Let N be the number of nodes and L the number of leaves. Each search from the root can visit all N nodes, and there are L searches, so the work is O(L * N). L is at most N, which gives O(N^2) in the worst case. The extra space is the recursion stack, at most the tree height, plus the list of leaves, which is at most N, so the space is O(N).

PythonTested in our runner

from typing import List, Optional

class Solution:
    def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
        if root is None:
            return []

        leaves = []

        # Walk the tree once and collect every leaf node.
        def collect(node):
            if node is None:
                return
            if node.left is None and node.right is None:
                leaves.append(node)
                return
            collect(node.left)
            collect(node.right)

        # Search from the root for the path that ends at target.
        def find(node, target):
            # Return the values from node down to target, or None.
            if node is None:
                return None
            if node is target:
                return [node.val]
            for child in (node.left, node.right):
                sub = find(child, target)
                if sub is not None:
                    return [node.val] + sub
            return None

        collect(root)  # the missing step: gather leaves from the root

        result = []
        for leaf in leaves:
            vals = find(root, leaf)
            result.append("->".join(str(v) for v in vals))
        return result

The Recursive Preorder Traversal infographic is part of Pro

A one-page visual of the pattern: when it applies, the steps and the invariant to keep.

Unlock the infographic

Solution pattern

Recursive Preorder Traversal

Part of Tree Traversal Patterns (DFS & BFS)

Approach 2: Recursive DFS with a shared path and backtrackingOptimalRecursive Preorder Traversal

The brute force search repeats the same descent for every leaf. Each search walks from the root again, so the top of the tree is scanned many times.

The insight that fixes this is that the path to a node is the path to its parent plus one value. A single DFS can keep one list with the current path. It appends on the way down, records the joined path at each leaf, and removes the value on the way back up. Every node is pushed and popped exactly once.

Why it is correct. At every call, the list holds exactly the values from the root down to the parent of the current node. So when a leaf is reached, the list is exactly that leaf's root-to-leaf path. Popping after both children restores the list, so the sibling subtree starts from the correct prefix.

Steps

  1. Create an empty result list and an empty path list.
  2. Call dfs on the root.
  3. In dfs, return immediately if the node is null.
  4. Append the node value to the path list.
  5. If the node is a leaf, join the path with "->" and add the string to the result. Otherwise call dfs on the left child, then on the right child.
  6. Remove the last value from the path list before returning.

Dry run

Trace on the example tree 1 -> 2 -> 3 along right children.

StepCallPath list after pushAction
1dfs(1)[1]not a leaf, go left
2dfs(null)[1]return
3dfs(1), right[1]go right, call dfs(2)
4dfs(2)[1, 2]not a leaf, go left
5dfs(null)[1, 2]return
6dfs(2), right[1, 2]go right, call dfs(3)
7dfs(3)[1, 2, 3]leaf, add "1->2->3"
8dfs(3) returns[1, 2]pop 3
9dfs(2) returns[1]pop 2
10dfs(1) returns[]pop 1

The result is ["1->2->3"]. The list is empty again at the end, so the state is clean for the next call.

Complexity

TimeO(N * h), where h is the tree height
SpaceO(h) auxiliary, excluding the output strings

Let N be the number of nodes, L the number of leaves and h the height. Each node is pushed once and popped once, which is O(N) work for the traversal. At each leaf, the join costs up to h steps, so the leaves add O(L * h), which is at most O(N * h) and O(N log N) for a balanced tree. The auxiliary space is the recursion stack plus the path list, and both hold at most h values, so the space is O(h).

PythonTested in our runner

class Solution:
    def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
        result = []
        path = []

        def dfs(node):
            if node is None:
                return
            path.append(str(node.val))
            if node.left is None and node.right is None:
                result.append("->".join(path))
            else:
                dfs(node.left)
                dfs(node.right)
            # Undo this node before returning to the parent.
            path.pop()

        dfs(root)
        return result

Common mistakes

  • Adding the path at every node instead of only at leaves, as in result.append(...) before the leaf check. The output then contains prefixes such as "1->2". Record the path only when both children are missing.
  • Adding "->" after every value, including the last one. The string ends with an arrow. Join the values with the separator instead of appending it blindly.
  • Forgetting the path.pop() (or remove) step in the shared-list version. The values from one branch leak into the sibling branch, so paths like "1->2->3->5" appear. Undo every push before returning.
  • Popping the value before the leaf check, or popping only on one branch. The list is then empty or stale when the parent reads it. Pop once, after both children return.
  • Dereferencing a null child without a check, for example node.left.val in the parent. Check for null at the start of dfs and return early.
  • Joining the path with str(path) or toString() of a list instead of joining the elements. You get brackets and commas in the output. Use the language's join function on the string elements.

Edge cases

  • A single node, root = [1]. The only node is a leaf, so the output is ["1"] with no arrow.
  • A chain that goes only left, or only right, such as [1, 2, null, 3]. There is one leaf and the path is the whole chain.
  • Negative values, such as [-1, -2, 3]. The string keeps the minus sign, giving "-1->-2" and "-1->3".
  • Repeated values, such as [1, 1, 1]. The paths must still be distinct by position. The answer is "1->1" and "1->1", and the code must not use the value as an identity check.
  • A node with exactly one child, such as [1, 2]. Node 1 is not a leaf, so it produces no answer. The only path is "1->2".
  • A maximum-size skewed tree of 100 nodes. The recursion depth is 100, which is safe, and the output holds one string of 100 values.

Follow-ups interviewers ask

Follow-ups are part of Pro

The questions interviewers ask after you solve Binary Tree Paths, with how to answer them.

Unlock the follow-ups

Binary Tree Paths FAQ

What is the time complexity of Binary Tree Paths?

The optimal DFS runs in O(N * h) time, where N is the number of nodes and h is the tree height. Each node is pushed and popped once, and each leaf pays for joining its path. For a balanced tree this is O(N log N).

Why use DFS for Binary Tree Paths?

The answer needs every root-to-leaf path, so the traversal must reach every leaf. DFS follows one branch to its end before backing up, which matches how a path grows. Its shared list grows and shrinks with the recursion, so no per-path copies are needed on the way down.

Can Binary Tree Paths be solved in O(1) extra space?

Not with the standard approach. The recursion stack and the path list both take O(h) space in the worst case. Iterative traversals with parent pointers or Morris-style threading can reduce this, but they add complexity that rarely pays off in an interview.

Why does the output not include a trailing arrow?

The arrow is a separator, not a terminator. Joining the list with "->" places arrows only between values. Appending the arrow after each value would leave one at the end of every path.

Why must leaves be detected by missing children instead of a null value?

A null child is not a path end. A node with one child has a null on its other side, so checking for any null would miss real paths. A leaf is the node where both left and right are null.

Asked at

See which companies ask this — Pro

Practise it