Binary Tree Paths Visualizer & Step-by-Step Algorithm Solution

Find all root-to-leaf paths in a binary tree in any order using depth-first search and backtracking.

Category: backtracking | Difficulty: Easy

Tags: Backtracking, Tree, Depth-First Search, Binary Tree

Binary Tree Paths

1
2
5
3
Current Path (curr)
0
100%
state
nodenull
curr[]
pathString""
pathsFound0
result[]
rootVal1
Initialization
1/28
Explanation

Start binaryTreePaths on tree with root value 1.

Source Code
1function binaryTreePaths(root: TreeNode | null): string[] {
2 if (!root) return [];
3 const result: string[][] = [];
4
5 function dfs(node: TreeNode | null, curr: string[]) {
6 if (!node) return;
7 curr.push(String(node.val));
8
9 if (!node.left && !node.right) {
10 result.push([...curr]);
11 curr.pop();
12 return;
13 }
14
15 dfs(node.left, curr);
16 dfs(node.right, curr);
17 curr.pop();
18 }
19 dfs(root, []);
20 return result.map((arr) => arr.join("->"));
21}