LeetCode #257 Easy

Binary Tree Paths

Binary Tree Paths is LeetCode 257 (Easy). Given the root of a binary tree, return all root-to-leaf paths, in any order, with the values on each path joined by "->".

  • A leaf is a node with no children.
  • The tree has 1 to 100 nodes, so root is never empty.

The answer has one string per leaf, so the work is one walk that visits each node once.

Constraints
  • The number of nodes in the tree is in the range [1, 100].
  • -100 <= Node.val <= 100
treedfsbacktracking
Open on LeetCode ↗
02

Intuition

A depth-first search follows one branch from the root all the way down before trying the next, which is exactly the shape of a root-to-leaf path. So a single list can hold the path to the node the search is on: it grows by one value on the way down and shrinks by one on the way back up.

That undo is what makes one list enough. When the search returns from a subtree, the list is exactly what it was before it went in, so the next branch starts from the right prefix. And whenever the search stands on a leaf, the list is a complete path.

How to spot this pattern

Use this add, act at the leaf, remove pattern whenever the answer is a set of whole root-to-leaf routes. Path Sum II (routes with a target sum), Sum Root to Leaf Numbers and Smallest String Starting From Leaf all reuse it; only what happens at the leaf changes.

03

Approach

Try it first

Before reading on: in [1,2,3,null,5], after "1->2->5" is saved, the search goes back to 1 and then right to 3. What must the path list hold just before 3 is added, and which values had to be removed to get there?

1

Add the node to the path

dfs(node) appends str(node.val) to path. The list now spells the route from the root to this node, so no parent pointers are needed to know how you got here.

2

Save the path at a leaf

If the node has no left and no right child, the route is complete: append "->".join(path) to the answer. Joining makes a new string, so later changes to path do not touch the saved one.

3

Visit each child that exists

Call dfs on the left child, then on the right child, skipping a child that is empty. Every call therefore gets a real node, and the left-to-right order puts the paths in the order of their leaves.

4

Remove the node before returning

Pop the last value from path. Every path through this node is already saved, and the pop returns the list to its parent's route, so the parent's next child starts from the right prefix.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
▶3 paths, path = [], []
▶4 
▶5 def dfs(node):
▶6 path.append(str(node.val))
▶7 if not node.left and not node.right:
▶8 paths.append("->".join(path))
▶9 if node.left:
▶10 dfs(node.left)
▶11 if node.right:
▶12 dfs(node.right)
▶13 path.pop()
▶14 
▶15 dfs(root)
▶16 return paths
finishedon path1235path1pathsemptyadd 1 to the path
node1has children
path"1"root down to this node
Start at the root. Its value 1 begins the path. The path list always spells the route from the root to the node being visited.
finishedon path1235path1pathsemptygo left to 2
calldfs(2)left child of 1
path"1"shared by every call
1 is not a leaf, so the search goes down. It tries the left child 2 first.
finishedon path1235path12pathsemptyadd 2 to the path
node2has children
path"1->2"root down to this node
Append 2. The path now reads "1->2", the route from the root down to this node.
finishedon path1235path12pathsemptygo right to 5
calldfs(5)right child of 2
path"1->2"shared by every call
2 has no left child, so that call is skipped and the search goes straight to the right child 5.
finishedon path1235path125pathsemptyadd 5 to the path
node5no children: a leaf
path"1->2->5"root down to this node
Append 5. The path now reads "1->2->5", the route from the root down to this node.
finishedon path1235path125paths1 → 2 → 55 is a leaf → save 1 → 2 → 5
saved"1->2->5"
paths1 of 2
5 has no children, so the route ends here. Join the path with "->" and save "1->2->5". The path itself stays as it is; the next steps shrink it on the way back up.
finishedon path1235path12paths1 → 2 → 5remove 5, back to 2
removed5all paths through it are done
path"1->2"
Every path through 5 is finished, so remove it. The list is back to "1->2", the route to 2, which has no branch left to try.
finishedon path1235path1paths1 → 2 → 5remove 2, back to 1
removed2all paths through it are done
path"1"
Every path through 2 is finished, so remove it. The list is back to "1", so the right branch of 1 starts from the correct prefix; without the pop, 2 would leak into those paths.
finishedon path1235path1paths1 → 2 → 5go right to 3
calldfs(3)right child of 1
path"1"shared by every call
The left side of 1 is finished and the path is back to "1". Now go right to 3.
finishedon path1235path13paths1 → 2 → 5add 3 to the path
node3no children: a leaf
path"1->3"root down to this node
Append 3. The path now reads "1->3", the route from the root down to this node.
finishedon path1235path13paths1 → 2 → 51 → 33 is a leaf → save 1 → 3
saved"1->3"
paths2 of 2
3 has no children, so the route ends here. Join the path with "->" and save "1->3". The path itself stays as it is; the next steps shrink it on the way back up.
finishedon path1235path1paths1 → 2 → 51 → 3remove 3, back to 1
removed3all paths through it are done
path"1"
Every path through 3 is finished, so remove it. The list is back to "1", the route to 1, which has no branch left to try.
finishedon path1235pathemptypaths1 → 2 → 51 → 3remove 1, back to the start
removed1all paths through it are done
pathempty
Remove the root too. The path is empty again, because every route has been explored.
finishedon path1235pathemptypaths1 → 2 → 51 → 3return 2 paths
paths["1->2->5", "1->3"]
leaves2one path per leaf
Done. There is one path per leaf, and each node was added once and removed once. The list holds 2 paths, in left-to-right order.
05

Common pitfalls

Not removing the node after its subtrees

✗ Wrong
path.append(str(node.val))
if node.left:
    dfs(node.left)
if node.right:
    dfs(node.right)
✓ Right
path.append(str(node.val))
if node.left:
    dfs(node.left)
if node.right:
    dfs(node.right)
path.pop()

Values from finished branches stay in the shared list. For [1,2,3,null,5] the second path comes out "1->2->5->3" instead of "1->3".

Saving the path when a child is empty

✗ Wrong
def dfs(node):
    if not node:
        paths.append("->".join(path))
        return
✓ Right
if not node.left and not node.right:
    paths.append("->".join(path))

A leaf has two empty children, so its path is saved twice. A node with only one child also saves a path that stops at it, even though it is not a leaf. Test the node itself for having no children.

06

Complexity

Time
O(n·h)
Space
O(h)
Each node is added and removed once, and each leaf costs one join of up to h values, so the time is about the size of the output itself. The path list and the call stack each hold one root-to-node route.
07

Binary Tree Paths FAQ

Is GFG Root to Leaf Paths the same problem?

Yes, with a different output. GeeksforGeeks' Root to Leaf Paths returns each path as a list of node values instead of a "->" string, so save path[:] (a copy of the list) at the leaf instead of joining it. The rest of the search is the same.

Is backtracking needed, or can each call get a new string?

Passing path + str(node.val) + "->" also works, and nothing has to be removed, because each call gets its own copy. The cost is a new string at every call, up to h characters long. The shared list with an undo builds a string only once per leaf, which keeps the extra space at O(h).

Can the paths be found without recursion?

Yes. Keep a stack of (node, path string) pairs, starting with (root, str(root.val)). Pop a pair; at a leaf save the string, otherwise push each child with path + "->" + str(child.val). Push the right child first so the left paths are saved first.