Binary Tree Paths
LeetCode 257 | Difficulty: Easyβ
EasyProblem Descriptionβ
Given the root of a binary tree, return *all root-to-leaf paths in any order*.
A leaf is a node with no children.
Example 1:

Input: root = [1,2,3,null,5]
Output: ["1->2->5","1->3"]
Example 2:
Input: root = [1]
Output: ["1"]
Constraints:
- The number of nodes in the tree is in the range `[1, 100]`.
- `-100 <= Node.val <= 100`
Topics: String, Backtracking, Tree, Depth-First Search, Binary Tree
Approachβ
Backtrackingβ
Explore all candidates by building solutions incrementally. At each step, choose an option, explore further, then unchoose (backtrack) to try the next option. Prune branches that can't lead to valid solutions.
Generate all combinations/permutations, or find solutions that satisfy constraints.
Tree DFSβ
Traverse the tree recursively (or with a stack). At each node, decide: what information do I need from the left/right subtrees? Process: go left β go right β combine results. Consider preorder, inorder, or postorder traversal based on when you need to process the node.
Path problems, subtree properties, tree structure manipulation.
String Processingβ
Consider character frequency counts, two-pointer approaches, or building strings efficiently. For pattern matching, think about KMP or rolling hash. For palindromes, expand from center or use DP.
Anagram detection, palindrome checking, string transformation, pattern matching.
Solutionsβ
Solution 1: C# (Best: 347 ms)β
| Metric | Value |
|---|---|
| Runtime | 347 ms |
| Memory | 41 MB |
| Date | 2022-01-10 |
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
public class Solution {
public IList<string> BinaryTreePaths(TreeNode root) {
List<string> result = new List<string>();
if(root == null) return result;
BinaryTreePathsUtil(root, "", result);
return result;
}
private void BinaryTreePathsUtil(TreeNode root, string path, List<string> result)
{
path += $"{root.val}";
if (root.left == null && root.right == null)
{
result.Add(path);
return;
}
path += "->";
if (root.left != null)
BinaryTreePathsUtil(root.left, path, result);
if (root.right != null)
BinaryTreePathsUtil(root.right, path, result);
}
}
Complexity Analysisβ
| Approach | Time | Space |
|---|---|---|
| Backtracking | $O(n! or 2^n)$ | $O(n)$ |
| Tree Traversal | $O(n)$ | $O(h)$ |
Interview Tipsβ
- Start by clarifying edge cases: empty input, single element, all duplicates.
- Consider: "What information do I need from each subtree?" β this defines your recursive return value.
- Identify pruning conditions early to avoid exploring invalid branches.