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.

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)

Visualization

Tap to expand
12354๐ŸŒณ Discovered Paths:Path 1: "1โ†’2โ†’5"Path 2: "1โ†’2โ†’4"Path 3: "1โ†’3"Each path represents a complete lineagefrom ancestor to childless descendant
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.
Asked in
Google 45 Facebook 38 Amazon 42 Microsoft 35
89.6K Views
High Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen