Skip to main content

Binary Tree Paths

LeetCode 257 | Difficulty: Easy​

Easy

Problem 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.

When to use

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.

When to use

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.

When to use

Anagram detection, palindrome checking, string transformation, pattern matching.


Solutions​

Solution 1: C# (Best: 347 ms)​

MetricValue
Runtime347 ms
Memory41 MB
Date2022-01-10
Solution
/**
* 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​

ApproachTimeSpace
Backtracking$O(n! or 2^n)$$O(n)$
Tree Traversal$O(n)$$O(h)$

Interview Tips​

Key Points
  • 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.