Binary Tree Paths

List every route from the top of a binary tree down to a node with no children, written as text.

Given the root of a binary tree, return every path that starts at the root and ends at a leaf, a node with no children. Write each path as its node values joined by "->". The paths can come in any order.

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

The Idea

You have probably seen a file address such as Documents/Photos/2024/beach.jpg. It names every folder on the way, from the top folder down to the file. This problem asks for the same kind of address in a tree: every value on the way from the top node down to a node that has nothing below it.

The input [1, 2, 3, null, 5] of Example 1 lists the tree row by row. The first value, 1, is the top node, called the root. The next row holds the two children of 1: 2 on the left and 3 on the right. The third row starts with the children of 2. Its left child is missing, written null, and its right child is 5. The list then ends, so 3 and 5 have no children.

Nodes 3 and 5 are the leaves of this tree, so the answer has two paths: 1, 2, 5 and 1, 3. In a big tree, though, how do we collect every path without missing one, and without stopping one too early? Look at the picture below.

The tree of Example 1. Beside each node is the path so far: 1 has "1", 2 has "1->2" and is marked one child: not a leaf, 5 has "1->2->5" and 3 has "1->3", both marked leaf: saved.

The box beside each node holds its path so far. The box beside 1 holds "1". Moving down to 2 adds "->2", and moving on to 5 gives "1->2->5". Node 5 is marked "leaf: saved", so its text is one answer. Going from 1 to the right starts again from "1" and gives "1->3", also saved.

Node 2 is marked "one child: not a leaf". The route goes on through 2 to 5, so "1->2" is not a finished path. Notice also that every node's path is its parent's path plus its own value. If each node hands its path to its children, the text that reaches a leaf is a complete answer.

To reach every leaf, the walk goes as deep as it can on the left side first, then comes back up and tries the right side. In Example 1 that order is 1, 2, 5, then 3. Walking a tree this way is called a depth-first walk.

Solution Approach

Turning that idea into code means settling three things: how to visit every node, how to hand the path text from a node to its children, and where a path ends.

Visiting every node

How does the walk reach every node in that order? A method walk(node, soFar, paths) gets a node, its path so far and the list of finished paths. It handles that node, then calls itself on the left child and then on the right child. Because the method calls itself for each child, it is recursive. The call for the left child returns only after it has handled everything below it, so all of the left side is done before the right side starts.

A missing child arrives as null. The call for it simply returns, because there is nothing on that side to add.

Handing the path to the children

How does the text travel down? It is the parameter soFar, a String. For the root, soFar is empty, so the root's value is written alone. Every later node adds "->" and its value, so no path starts with an arrow.

A Java String never changes once it is made. Adding to it builds a new string, so the "1" that node 1 hands to 2 is still "1" when it hands the same text to 3. Nothing has to be taken back after the left side is done.

Where a path ends

When is a path finished? Only at a node whose left and right children are both missing. That node saves its path in the list paths and returns. Node 2 in Example 1 has a child, so it saves nothing and passes "1->2" on to 5.

Java Solution

The method binaryTreePaths and its helper walk work in these steps:

  1. First, binaryTreePaths creates the empty list paths and calls walk(root, "", paths), with an empty path so far.
  2. In walk, if node is null, return at once: there is no child on this side.
  3. Otherwise build path: the node's value alone when soFar is empty, else soFar + "->" + node.val.
  4. If node.left and node.right are both null, the node is a leaf: add path to paths and return.
  5. Otherwise call walk on node.left and then on node.right, handing path to both.
  6. When the first call to walk returns, paths holds every root-to-leaf path, and binaryTreePaths returns it.

The class also has a small TreeNode class, a build helper that makes a tree from the row-by-row form, and a show helper that prints the paths in quotes. The main method runs both examples, a full tree of three rows, a tree that only goes right, negative values and an empty tree.

Java
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class BinaryTreePaths {

    static class TreeNode {
        int val;
        TreeNode left, right;
        TreeNode(int val) { this.val = val; }
    }

    public static List<String> binaryTreePaths(TreeNode root) {
        List<String> paths = new ArrayList<>();
        walk(root, "", paths);
        return paths;
    }

    private static void walk(TreeNode node, String soFar, List<String> paths) {
        if (node == null) {
            return;                              // no child on this side
        }
        String path = soFar.isEmpty() ? String.valueOf(node.val) : soFar + "->" + node.val;
        if (node.left == null && node.right == null) {
            paths.add(path);                     // reached a leaf: the path is complete
            return;
        }
        walk(node.left, path, paths);
        walk(node.right, path, paths);
    }

    // Builds a tree from its row-by-row form, with null for a missing child.
    static TreeNode build(Integer... values) {
        if (values.length == 0 || values[0] == null) {
            return null;
        }
        TreeNode root = new TreeNode(values[0]);
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        int i = 1;
        while (i < values.length) {
            TreeNode parent = queue.poll();
            if (values[i] != null) {
                parent.left = new TreeNode(values[i]);
                queue.add(parent.left);
            }
            i++;
            if (i < values.length && values[i] != null) {
                parent.right = new TreeNode(values[i]);
                queue.add(parent.right);
            }
            i++;
        }
        return root;
    }

    static String show(List<String> paths) {
        List<String> quoted = new ArrayList<>();
        for (String p : paths) {
            quoted.add("\"" + p + "\"");
        }
        return quoted.toString();
    }

    public static void main(String[] args) {
        System.out.println(show(binaryTreePaths(build(1, 2, 3, null, 5))));
        System.out.println(show(binaryTreePaths(build(1))));
        System.out.println(show(binaryTreePaths(build(1, 2, 3, 4, 5, 6, 7))));
        System.out.println(show(binaryTreePaths(build(1, null, 2, null, 3))));
        System.out.println(show(binaryTreePaths(build(-10, 20, -30))));
        System.out.println(show(binaryTreePaths(build())));
    }
}

Running it prints:

Output
["1->2->5", "1->3"]
["1"]
["1->2->4", "1->2->5", "1->3->6", "1->3->7"]
["1->2->3"]
["-10->20", "-10->-30"]
[]

The third line comes from [1, 2, 3, 4, 5, 6, 7], where 1 and 2 and 3 all have two children. Its four paths end at 4, 5, 6 and 7, in that order, because the walk finishes the left side of each node before its right side.

The fourth line comes from [1, null, 2, null, 3], where each node has only a right child. Nodes 1 and 2 save nothing, so the only path is "1->2->3". In the fifth line, "-10->-30" shows that a negative value is simply written after the arrow. The last line, [], is the empty tree: the first call gets null and returns at once.

What if the path were saved when the walk reaches null, instead of at a leaf? That version, run on Example 1, prints:

Output
[1->2, 1->2->5, 1->2->5, 1->3, 1->3]

Each leaf has two missing children, so "1->2->5" and "1->3" each appear twice. The missing left child of 2 also saves "1->2", a path that stops before its leaf. Checking for a leaf before going down avoids both.

Complexity

The walk visits each node once, but each visit builds a new path string, and that copying sets the cost.

  • Time: O(n × h), because walk runs once for each of the n nodes and copies the path so far, which holds up to h values, where h is the number of nodes on the longest root-to-leaf path.
  • Space: O(n × h), because a tree can have about n / 2 leaves and each saved path holds up to h values. Besides the output, the calls still waiting on the way down are at most h deep, each with its own path string.

Keeping only the paths whose values add up to a given sum is Path Sum II.