Ctrl K

Routes from Root to Leaves

Easy
You are given the root of a binary tree. A leaf is a node with no children. For every leaf, write down the route from the root to it as a string: the node values in order, joined by an arrow -> with no spaces, such as "8->5->2". Return a list of all these strings, one per leaf. The strings may come in any order.
Example 1
root=tree_node([8, 3, 5, None, None, 2, 7]) → ['8->3', '8->5->2', '8->5->7']

The leaves are 3, 2 and 7. The routes to them are 8->3, 8->5->2 and 8->5->7.

Example 2
root=tree_node([-4, None, 6]) → ['-4->6']

The only leaf is 6, reached by -4->6.

Example 3
root=tree_node([12]) → ['12']

The root is itself a leaf, so the route is just one node.

Constraints
  • 1 ≤ number of nodes ≤ 1000
  • -1000 ≤ Node.val ≤ 1000
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsSmallest Leaf-to-Root Word MediumAll Leaf Paths With a Given Total MediumTree From Bracket Notation MediumTree in Compact Brackets MediumTree From a Dashed Preorder Record Hard
loading Python…
Input
root=tree_node([8, 3, 5, None, None, 2, 7])
Expected
['8->3', '8->5->2', '8->5->7']

Run checks the first 3 tests in your browser. Submit checks all 82 tests on the server, hidden ones included.