Problem 476375 · easy · Level 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

    4
   / \
  9   2
     / \
    7   5
         \
          1

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

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…