Binary Tree Paths

Find all root to leaf paths

Easy
Difficulty
O(2^n)
Time Complexity
O(n)
Space Complexity
Backtracking & recursion
Approach
Jan 26, 2026
Last Updated

Problem Statement

Given the root of a binary tree, return all root-to-leaf paths in any order. A leaf is a node with no children.

Examples

Example 1:

Input: root = [1,2,3,null,5]

Output: ["1->2->5","1->3"]

Example 2:

Input: root = [1]

Output: ["1"]

Binary Tree Paths - Backtracking Approach

BacktrackingBinary Tree Paths - Backtracking Approach
1class Solution {
2
3    
4    List<String> list = new ArrayList<>();
5
6    public List<String> binaryTreePaths(TreeNode root) {
7        if (root == null) return list;
8
9        List<Integer> bits = new ArrayList<>();
10        bits.add(root.val);
11        combos(root, bits);
12        return list;
13    }
14
15    public void combos(TreeNode root, List<Integer> bits){
16        // base case
17        if (root.left == null && root.right == null){
18            StringBuilder sb = new StringBuilder();
19            for (int i=0; i<bits.size()-1; i++){
20                sb.append(bits.get(i)).append("->");
21            }
22            sb.append(bits.get(bits.size()-1));
23            list.add(sb.toString());
24            return;
25        }
26
27        // path 1
28        if (root.left != null){
29            bits.add(root.left.val);
30            combos(root.left, bits);
31            bits.remove(bits.size() - 1);
32        }
33
34        // path 2
35        if (root.right != null){
36            bits.add(root.right.val);
37            combos(root.right, bits);
38            bits.remove(bits.size() - 1);
39        }
40    }
41}