Skip to content
Problem 257 · LeetCode 257(opens in a new tab)

Binary Tree Paths

EasyBacktracking

Take a binary tree, with root as its top node. List 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 "->", for example "4->2". The paths can be returned in any order.

Example 1

Input:  root = [4, 7, 2, null, 6]
Output: ["4->7->6", "4->2"]
Why:    6 and 2 are the only leaves
2 more examples and the constraints

Example 2

Input:  root = [8]
Output: ["8"]
Why:    the root is itself a leaf

Example 3

Input:  root = [-1, 5, -3, 2]
Output: ["-1->5->2", "-1->-3"]
Why:    negative values keep their minus sign

Constraints

  • 1 ≤ number of nodes ≤ 100
  • −100 ≤ node value ≤ 100

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. DFS, pass the path string downO(n · h)
  2. DFS with one shared pathO(n + L · h)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for a 100-node chainVerdict
DFS, pass the path string downO(n · h)
Passes; copies at every node
DFS with one shared pathO(n + L · h)
Best; copies only at leaves

n = nodes, h = height, L = leaves. The answer itself holds L strings of up to h values, so no method can beat O(L · h).

Edge cases to test

  • One node. The root is a leaf: the answer is just its value.
  • A chain. Only one leaf, so only one path, as long as the tree.
  • One child missing. A node with one child is not a leaf. In Example 1, 7 must not end a path.
  • Negative values. -1 then -3 is written "-1->-3"; the minus sign stays.

Common mistakes

  • Treating a null child as the end of a path, which records paths through nodes that still have a child.
  • Forgetting to pop after both children, so values from one branch leak into the next path.
  • Adding "->" after the last value, giving "4->2->".

How to talk through it

  1. 1Clarify. Can the tree be empty? Is a node with one child a leaf? Does the order of paths matter?
  2. 2Name the search. Each path is one walk from the root, so a DFS visits them all.
  3. 3Pass the string first. Copying the path into each call is simple and correct; mention that it copies at every node.
  4. 4Share one path. Push on entry, pop on exit, join only at a leaf.
  5. 5Test out loud. Run one node, a chain and a node with only a right child.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?