FastPrepRoot-to-Node Path in a Binary Tree
Problem · Tree

Root-to-Node Path in a Binary Tree

Learn this problem
EasyAmazon logoAmazonFULLTIMEONSITE INTERVIEW
See Amazon hiring insights

Problem statement

Given the root of a binary tree whose node values are unique and an integer target, return the node values along the path from the root to the node whose value equals target, including both endpoints.

If the target does not appear in the tree, return an empty array.

Function

rootToNodePath(root: TreeNode, target: int) → int[]

Examples

Example 1

root = [1,2,3,4,5,null,6]target = 5return = [1,2,5]

Starting at 1, move left to 2 and then right to 5.

Example 2

root = [7]target = 7return = [7]

The root is the target, so the path contains one value.

Example 3

root = [1,2,3]target = 9return = []

No node has value 9.

Constraints

  • The tree contains from 0 through 10^5 nodes.
  • -10^9 <= Node.val, target <= 10^9.
  • All node values are unique.

More Amazon problems

drafts saved locally
public int[] rootToNodePath(TreeNode root, int target) {
  // write your code here
}
root[1,2,3,4,5,null,6]
target5
expected[1,2,5]
checking account