oneby7

Binary Trees Depth first: return a value up

363. Path from the Root to a Node

Medium

You are given root, the root node of a binary tree, and an integer target. The values in the tree are distinct, and one node holds target. Return the values on the path from the root down to that node, in order. The path starts with the root's value and ends with target.

The tree is not a binary search tree. Its values can be in any order.

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

192674-38

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

Output: [4,9,6,7]

Explanation: 7 is the right child of 6, 6 is the right child of 9, and 9 is the left child of the root 4. The other nodes are not on the way down to 7.

Example 2

-505

Input: root = [0, -5, 5], target = 0

Output: [0]

Explanation: target is the root, so the path is the root alone.

Example 3

−10⁹710⁹

Input: root = [-1000000000, null, 1000000000, 7] target = 7

Output: [-1000000000,1000000000,7]

Explanation: The root has only a right child, 1000000000, and 7 is that child's left child.

Check your understanding

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

root = [10, 5, 15, 3, 20, 12], target = 20

Constraints

  • 1 ≤ number of nodes ≤ 105
  • -109 ≤ Node.val ≤ 109
  • The tree has at most 1000 levels.
  • All the values in the tree are distinct.
  • target is the value of a node in the tree.

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.