Binary Tree Paths (LeetCode 257): Solution and Explanation
Given a binary tree, list every path from the root down to a leaf. Each path is returned as a string of node values joined by arrows, such as 1->2->5, and the paths can come back in any order.
Watch it run step by step
Try your own input and write the code →Intuition
Any question that asks for every root-to-leaf path is a depth-first search question. DFS naturally follows one path from the root all the way down before backing up and trying the next branch, so at any moment the current call stack describes exactly one path.
All you need is a way to remember that path as you go. Since the answer is a string anyway, the reference solution carries a string down the recursion. Each call appends its own value to the string it received. If the node is a leaf, the string is a finished answer. If not, the call adds the arrow separator and hands the string to both children.
Because Python strings are immutable, path += str(root.val) creates a new string local to that call. That means you never have to undo anything when the recursion returns: the parent's path is untouched by whatever the children did. This is backtracking without an explicit pop, at the cost of building a new string at each node.
Adding the arrow only for non-leaf nodes is what keeps the output clean. A leaf ends its path with its own value and no trailing separator, so there is no need to trim anything afterward.
Approach: DFS with string accumulation
- If the root is
None, return an empty list. - Create
pathsand definedfs(root, path), which returns immediately on aNonenode. - Append the node's value to the path with
path += str(root.val). - If the node is a leaf, add
pathtopaths, since it is a complete root-to-leaf string. - Otherwise append the
->separator and calldfson the left child and then the right child with the extended string. - Call
dfs(root, "")and returnpaths.
Step-by-step example
root = [1,2,3,null,5]
- At node 1 the path becomes
1. It has children, so the path becomes1->and the search goes left. - At node 2 the path becomes
1->2. Node 2 has a right child, so it is not a leaf, and the path becomes1->2->. - The left child of 2 is
None, so that call returns at once. The right child is 5. - At node 5 the path becomes
1->2->5. It is a leaf, so it is added topaths. - Back at node 1, its own local path is still
1->. At node 3 it becomes1->3, which is a leaf, so it is added. - The result is [
1->2->5,1->3].
Code: Python, Java, C++
1class Solution:
2 def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
3 if not root:
4 return []
5
6 paths = []
7
8 def dfs(root, path):
9 if not root:
10 return
11
12 path += str(root.val)
13
14 if not root.left and not root.right:
15 paths.append(path)
16 else:
17 path += "->"
18 dfs(root.left, path)
19 dfs(root.right, path)
20
21 dfs(root, "")
22 return paths1class Solution {
2 public List<String> binaryTreePaths(TreeNode root) {
3 List<String> paths = new ArrayList<>();
4 if (root != null) dfs(root, "", paths);
5 return paths;
6 }
7
8 private void dfs(TreeNode root, String path, List<String> paths) {
9 if (root.left == null && root.right == null) {
10 paths.add(path + root.val);
11 }
12 if (root.left != null) {
13 dfs(root.left, path + root.val + "->", paths);
14 }
15 if (root.right != null) {
16 dfs(root.right, path + root.val + "->", paths);
17 }
18 }
19}1class Solution {
2public:
3 vector<string> binaryTreePaths(TreeNode* root) {
4 vector<string> paths;
5 if (root) dfs(root, "", paths);
6 return paths;
7 }
8
9 void dfs(TreeNode* root, string path, vector<string>& paths) {
10 if (!root->left && !root->right) {
11 paths.push_back(path + to_string(root->val));
12 }
13 if (root->left) {
14 dfs(root->left, path + to_string(root->val) + "->", paths);
15 }
16 if (root->right) {
17 dfs(root->right, path + to_string(root->val) + "->", paths);
18 }
19 }
20};Time and space complexity
O(n²)
Every node is visited once, but building the string at a node copies a path of length up to the height h. That gives O(n × h), which is O(n²) for a skewed tree and O(n log n) for a balanced one.
O(h²)
The recursion is h calls deep and each frame holds its own string of length up to O(h). The output is not counted, though in the worst case it also holds O(n²) characters.
Other approaches
Backtracking with a list of values (time O(n × h), space O(h))
Keep one shared list of node values, append on the way down and pop on the way back up, and only join it into a string with arrows when you reach a leaf. This avoids rebuilding strings at internal nodes, so the extra work is only paid for real answers.
Iterative DFS with a stack (time O(n²), space O(n²))
Push pairs of (node, path string) onto a stack, pop them one at a time, and push children with the extended string. It produces the same answers without recursion, which helps on very deep trees.
Common mistakes
- Adding the arrow before checking for a leaf, which leaves a trailing
->on every path. - Recording a path at any node with a missing child. A node with one child is not a leaf, and doing so produces paths that stop early.
- Using a shared mutable list without popping after the recursive calls, so values from one branch leak into the next path.
- Forgetting to convert values with
str(), which raises a type error when concatenating an integer to a string.
Frequently asked questions
Why don't we need to undo the path in this solution?
Strings in Python are immutable, so path += str(root.val) makes a new string for that call only. When the call returns, the parent still has its original string, so there is nothing to remove.
What is the time complexity of Binary Tree Paths?
Visiting nodes is O(n), but copying the path string at each node costs up to O(h). Together that is O(n × h), which is O(n²) in the worst case.
Can Binary Tree Paths be solved with BFS?
Yes. Keep a queue of (node, path so far) pairs and add a path to the answer whenever you pop a leaf. The paths come out ordered by depth rather than left to right, which is fine because any order is accepted.