Problem · Tree
Root-to-Node Path in a Binary Tree
Learn this problemProblem 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
0through10^5nodes. -10^9 <= Node.val, target <= 10^9.- All node values are unique.