EasyNeetCode150StringTreeDepth-First SearchBinary Tree

Binary Tree Paths

Return all root-to-leaf paths.

Examples

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

Two paths.

Constraints

  • Number of nodes in [1,100]
  • -100 <= Node.val <= 100

Approaches

Recursively build paths.

CodeT: O(n^2) | S: O(n) stack depth + paths

Same approach.

CodeT: O(n^2) | S: O(n)

Join path string.

CodeT: O(n^2) | S: O(n)

Complexity Comparison

DFS
T: O(n^2)S: O(n) stack depth + paths

Recursively build paths.

DFS Optimized
T: O(n^2)S: O(n)

Same approach.

DFS with String Building
T: O(n^2)S: O(n)

Join path string.

Common Mistakes

Not checking leaf node

Not handling single node

Path separator wrong

Try It Yourself

Copy the optimal solution and run it in our compiler.

Open in Compiler