Problem 476375 · easy · Phase 04 Non-Linear Data Structures

Root-to-Leaf Path Strings

binary tree · recursion · backtracking · strings

Given the root of a binary tree, return every root-to-leaf path as a string whose values are joined by ->. A leaf is a node with no children. The paths may be returned in any order; an empty tree has no paths.

Examples

    1
   / \
  2   3
   \
    5

Input:  root = build_tree([1, 2, 3, None, 5])
Output: ["1->2->5", "1->3"]

Input:  root = build_tree([7])
Output: ["7"]

Constraints

  • 0 <= number of nodes <= 1000
  • -100 <= node.val <= 100

Goals

  • Carry the path built so far down a recursive call
  • Recognise a leaf as the moment to record a finished path
Starting Python…