Given the root of a binary tree, return all root-to-leaf paths in any order.

A leaf is a node with no children.

Input & Output

Example 1 — Basic Binary Tree
$ Input: root = [1,2,3,null,5]
Output: ["1->2->5","1->3"]
💡 Note: Tree has two root-to-leaf paths: 1→2→5 (left subtree) and 1→3 (right subtree)
Example 2 — Single Node Tree
$ Input: root = [1]
Output: ["1"]
💡 Note: Tree with only root node - the single path is just the root value
Example 3 — Complete Binary Tree
$ Input: root = [1,2,3,4,5]
Output: ["1->2->4","1->2->5","1->3"]
💡 Note: Three root-to-leaf paths: left-left (1→2→4), left-right (1→2→5), and right (1→3)

Constraints

  • The number of nodes in the tree is in the range [1, 100]
  • -100 ≤ Node.val ≤ 100

Visualization

Tap to expand
Binary Tree Paths INPUT 1 2 3 leaf 5 leaf root = [1,2,3,null,5] Green nodes = leaves ALGORITHM STEPS 1 Start DFS at root path = [1] 2 Explore left child path = [1, 2] 3 Reach leaf (node 5) path = [1, 2, 5] Save: "1-->2-->5" 4 Backtrack, go right path = [1, 3] Save: "1-->3" Backtracking restores path for other branches FINAL RESULT 1 2 3 5 Output: "1-->2-->5" "1-->3" OK - 2 paths found Key Insight: DFS explores each path from root to leaf. When we reach a leaf node (no children), we save the current path. Backtracking removes the last node from path list, allowing us to explore other branches without creating new path copies each time. TutorialsPoint - Binary Tree Paths | DFS with Path List and Backtracking
Asked in
Google 45 Facebook 38 Amazon 32 Apple 28
285.0K Views
Medium Frequency
~15 min Avg. Time
4.2K 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