Binary Tree Paths

All root-to-leaf paths in a binary tree — DFS with path-building.

Easy
Time O(n) Space O(n)
LeetCode
3 min read
backtracking tree dfs

Problem#

Return all root-to-leaf paths as strings ("1->2->3" format).

Examples#

  • [1,2,3,null,5]["1->2->5","1->3"]

Constraints#

  • 1 <= n <= 100.

Approach#

DFS carrying the current path. At a leaf, emit. The path can be passed by reference with push/pop, or by value (creating a new string each recursion).

Solution#

Binary Tree Paths
class Solution {
public:
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> out;
function<void(TreeNode*, string)> dfs = [&](TreeNode* n, string path) {
if (!n) return;
if (!path.empty()) path += "->";
path += to_string(n->val);
if (!n->left && !n->right) { out.push_back(path); return; }
dfs(n->left, path);
dfs(n->right, path);
};
dfs(root, "");
return out;
}
};

Editorial#

Passing path by value avoids the explicit pop on backtrack — each recursive call gets its own copy. For larger paths, pass by reference and manage push/pop manually.

Complexity#

  • Time: O(n).
  • Space: O(n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.