AAlgoLoopSpaced repetition for LeetCode
EASYTree / RecursionLeetCode ↗

Binary Tree Paths

The key idea

Walk the tree depth-first, carrying the path of values seen so far. A node with no children is a leaf, so join the accumulated values with -> and record that one path. The recursion's own call stack tracks the current path for you.

Problem

Given the root of a binary tree, return all the root-to-leaf paths in any order.

A leaf is a node with no children. Each path is the sequence of node values from root down to a leaf, written as the values joined by -> (for example, 1->2->5).

Constraints

Examples

Input: root = [1,2,3,null,5] Output: ["1->2->5","1->3"]
Input: root = [1] Output: ["1"]

Complexity

Time: O(n) Space: O(n)

See the full solution

410310
Step-by-step visualization
Start free →

More Tree / Recursion problems