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 "->"
Example 1
Output: ["1->2->5", "1->3"]
Example 2
Output: ["1"]
The Idea
You have probably seen a file address such as Documents/Photos/2024/beach.jpg
The input [1, 2, 3, null, 5]null
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 box beside each node holds its path so far. The box beside 1 holds "1""->2""1->2->5""1""1->3"
Node 2 is marked "one child: not a leaf". The route goes on through 2 to 5, so "1->2"
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)
A missing child arrives as null
Handing the path to the children
How does the text travel down? It is the parameter soFarStringsoFar"->"
A Java String"1""1"
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"1->2"
Java Solution
The method binaryTreePathswalk
- First,
creates the empty listbinaryTreePaths and callspaths , with an empty path so far.walk(root, "", paths) - In
, ifwalk isnode , return at once: there is no child on this side.null - Otherwise build
: the node's value alone whenpath is empty, elsesoFar .soFar + "->" + node.val - If
andnode.left are bothnode.right , the node is a leaf: addnull topath and return.paths - Otherwise call
onwalk and then onnode.left , handingnode.right to both.path - When the first call to
returns,walk holds every root-to-leaf path, andpaths returns it.binaryTreePaths
The class also has a small TreeNodebuildshowmain
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:
["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]
The fourth line comes from [1, null, 2, null, 3]"1->2->3""-10->-30"[]null
What if the path were saved when the walk reaches null
[1->2, 1->2->5, 1->2->5, 1->3, 1->3]
Each leaf has two missing children, so "1->2->5""1->3""1->2"
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
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.walk - 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