Given the root of a binary tree and an integer target, return the path from the root to the node with value target.
The path is a list of node values from the root to the target node, inclusive. If no node has the value target, return an empty list. All node values in the tree are unique.
Function Signature
def root_to_node_path(root: TreeNode, target: int) -> list[int]:
Rules
-
TreeNode
has the fields
val
,
left
and
right
. A missing child is
None
.
-
The examples write the tree as a level-order list in which
None
marks a missing child. Children of a missing node are not listed, and trailing
None
values are dropped.
-
The tree is a plain binary tree with no ordering between parent and child values, so it is not a binary search tree.
-
If
target
is the root's value, the answer is
[root.val]
.
-
Values are unique, so at most one node matches and the answer is unique.
Constraints
-
The number of nodes in the tree is in the range
[1, 10^4]
.
-
-10^5 <= Node.val <= 10^5
-
All node values are unique.
-
-10^5 <= target <= 10^5
Examples
Input: root = [1,2,3,4,5,6,7], target = 5
Output: [1,2,5]
The root 1 has children 2 and 3, and node 2 has children 4 and 5. Node 5 is reached through 2, so the path is 1, 2, 5.
Input: root = [1,2,3,None,None,4,5], target = 4
Output: [1,3,4]
Node 2 has no children, and node 3 has children 4 and 5. Node 4 is the left child of 3, which is the right child of 1.
Input: root = [1,2,3], target = 4
Output: []
The tree holds only 1, 2 and 3, so no node has value 4.