Katkat

Return all root-to-leaf tree paths

Capital OneMachine Learning Engineer · Onsite

Last updated

This question evaluates competence with binary tree structures, path enumeration and traversal techniques along with the ability to represent traversal results as formatted strings.

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

  • A leaf is a node with no children.
  • A path should be represented as a string with node values separated by "->".

Input

  • root: the root node of a binary tree (each node has val, left, right).

Output

  • A list of strings, each string representing one root-to-leaf path.

Example

For the tree:

 1
 / \
 2 3
 \
 5

Output:

  • ["1->2->5", "1->3"]

Constraints

  • Number of nodes up to 10^4.
  • Node values are integers.