Binary Tree Paths
Easy · Trees · String · Backtracking · Tree · Depth-First Search · Binary Tree
Problem
Given the root of a binary tree, return every root-to-leaf path as a string, in any order.
Write each path as its node values joined by "->", for example "1->4->7". A leaf is a node with no children.
The tests build trees with from_level([...]), a level-order list where None marks a missing child.
Examples
Input: root = [7,3,9,null,5] Output: ["7->3->5","7->9"]
There are two leaves, 5 and 9, giving two paths.
Input: root = [-4] Output: ["-4"]
The root alone is a leaf.
Constraints
- 1 <= number of nodes <= 100
- -100 <= Node.val <= 100
Approaches
- Baseline: climb from every leaf to the root — time O(n · h), space O(n)
Follow-up
What if you only wanted the paths to the deepest leaves, or the paths with the largest sum? The same walk works with one more number carried down (see the use cases).
Related problems
Start free on Cariara · Coding problems · System design studio