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
rootis never empty.
The answer has one string per leaf, so the work is one walk that visits each node once.
- The number of nodes in the tree is in the range [1, 100].
- -100 <= Node.val <= 100
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.
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.
Approach
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?
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.
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.
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.
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.
Code in Python, C++ and Java
"->" and save "1->2->5". The path itself stays as it is; the next steps shrink it on the way back up."->" and save "1->3". The path itself stays as it is; the next steps shrink it on the way back up."->" and save "1". The path itself stays as it is; the next steps shrink it on the way back up."->" and save "1->2->4". The path itself stays as it is; the next steps shrink it on the way back up."->" and save "1->2->5". The path itself stays as it is; the next steps shrink it on the way back up."->" and save "1->3". The path itself stays as it is; the next steps shrink it on the way back up.Common pitfalls
Not removing the node after its subtrees
path.append(str(node.val))
if node.left:
dfs(node.left)
if node.right:
dfs(node.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
def dfs(node):
if not node:
paths.append("->".join(path))
returnif 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.
Complexity
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.