Binary Tree Paths - Problem
Binary Tree Paths is a fundamental tree traversal problem that asks you to find all possible routes from the root to every leaf node.
Given the
root of a binary tree, your task is to return all root-to-leaf paths in any order. A leaf is defined as a node that has no children (both left and right children are null).
Goal: Collect every unique path from root to leaf as a string representation.
Input: Root node of a binary tree
Output: Array of strings, where each string represents a path from root to leaf
For example, if you have a tree with root value 1, left child 2, and right child 3, the paths would be ["1->2", "1->3"] (assuming 2 and 3 are leaf nodes). Input & Output
example_1.py โ Basic Binary Tree
$
Input:
root = [1,2,3,null,5]
โบ
Output:
["1->2->5","1->3"]
๐ก Note:
Tree has two paths from root to leaves: 1->2->5 (left path through node 2 to leaf 5) and 1->3 (right path directly to leaf 3)
example_2.py โ Single Node Tree
$
Input:
root = [1]
โบ
Output:
["1"]
๐ก Note:
Tree contains only the root node, which is also a leaf. The single path is just the root value.
example_3.py โ Linear Tree
$
Input:
root = [1,2,null,3,null,4]
โบ
Output:
["1->2->3->4"]
๐ก Note:
Tree forms a linear chain going left at each level. Only one path exists from root 1 to the single leaf 4.
Visualization
Tap to expand
Understanding the Visualization
1
Start Exploration
Begin at the family patriarch/matriarch (root node)
2
Follow Lineages
Trace down each branch, recording names along the way
3
Record Complete Lines
When reaching someone with no children (leaf), save the full lineage
4
Backtrack
Return to previous generation and explore other branches
Key Takeaway
๐ฏ Key Insight: DFS with backtracking builds paths incrementally in one traversal, making it optimal for tree path discovery problems.
Time & Space Complexity
Time Complexity
O(n)
Single traversal visiting each node exactly once
โ Linear Growth
Space Complexity
O(h)
Recursion stack depth equals tree height, plus space for current path
โ Linear Space
Constraints
- The number of nodes in the tree is in the range [0, 100]
- Node values are in the range [-100, 100]
- All node values are unique
- Tree can be empty (root = null)
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code