oneby7

Binary Trees Depth first: return a value up

351. Binary Tree Paths

Easy

You are given root, the root node of a binary tree. Return every root-to-leaf path in the tree. Write each path as a string of the node values from the root down to the leaf, with -> between two values and no spaces, such as "3->-8->5".

A leaf is a node with no children. A root-to-leaf path starts at the root and goes down, one child at a time, until it reaches a leaf. A node with only one child is not a leaf, so a path cannot stop there. Two paths that end at different leaves are different paths, even when they hold the same values, so both are listed. An empty tree has no paths, and its answer is [].

The paths can come back in any order, and any order is accepted. The examples list them in sorted order. Leave the tree as you found it.

The examples write a tree level by level, from left to right, with null where a child is missing. So root = [5,8,null,3] is the root 5 with a left child 8 and no right child, and 8 has a left child 3. The missing children after the last node are left out.

Example 1

7-243196

Input: root = [4, -2, 9, 7, null, 3, 6, null, null, null, 1]

Output: ["4->-2->7","4->9->3->1","4->9->6"]

Explanation: The tree has three leaves: 7, 1 and 6. The nodes −2 and 3 have one child each, so the paths go on through them. A negative value keeps its minus sign, which gives ->-2 in the first path.

Example 2

Input: root = []

Output: []

Explanation: The tree is empty, so it has no root-to-leaf paths.

Example 3

3−10⁹3

Input: root = [-1000000000, 3, 3]

Output: ["-1000000000->3","-1000000000->3"]

Explanation: The two paths hold the same values, but they end at different leaves, so the answer lists both.

Check your understanding

Work out the answer for this input before you write any code.

root = [1, 2, 3, null, 5]

Constraints

  • 0 ≤ number of nodes ≤ 105
  • -109 ≤ Node.val ≤ 109
  • The tree has at most 1000 levels.
  • The paths in the answer hold at most 106 values in all.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.