Leetcode #257: Binary Tree Paths
In this guide, we solve Leetcode #257 Binary Tree Paths in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

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.
Quick Facts
- Difficulty: Easy
- Premium: No
- Tags: Tree, Depth-First Search, String, Backtracking, Binary Tree
Intuition
We must explore combinations of choices, but many branches can be pruned early.
Backtracking enumerates valid candidates while keeping the search space under control.
Approach
Use DFS to build candidates step by step, and backtrack when constraints are violated.
Pruning keeps the exploration practical for typical constraints.
Steps:
- Define the decision tree.
- DFS through choices and backtrack.
- Prune invalid paths early.
Example
Input: root = [1,2,3,null,5]
Output: ["1->2->5","1->3"]
Python Solution
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
def dfs(root: Optional[TreeNode]):
if root is None:
return
t.append(str(root.val))
if root.left is None and root.right is None:
ans.append("->".join(t))
else:
dfs(root.left)
dfs(root.right)
t.pop()
ans = []
t = []
dfs(root)
return ans
Complexity
The time complexity is , and the space complexity is . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.