#K48817. Find Path in Binary Tree
Find Path in Binary Tree
Find Path in Binary Tree
Given a binary tree and a target value, your task is to find the unique path from the root of the tree to the node that contains the target value. If the target value is not present in the tree, output an empty line.
The binary tree is represented in level-order where the keyword null
denotes a missing child. More formally, if the binary tree is represented as an array A
, then for the node at index i
, its left child is at index 2i+1
and its right child is at index 2i+2
(if such indices exist and the node is not null
).
Input Format:
The first line contains the level-order representation of the tree where each token is separated by a space. The token null
represents a missing node. The second line contains one integer representing the target value.
Output Format:
Output the values along the path from the root to the target node, separated by a single space. If the target does not exist in the tree, output an empty line.
The problem can be formally formulated as follows:
Find a sequence \( P = [p_0, p_1, \dots, p_k] \) such that:
\[ \begin{aligned} p_0 &= \text{root},\\ p_k &= \text{target node},\\ \forall i,\,0\leq iinputFormat
The input consists of two lines:
- The first line contains the level-order traversal of the binary tree, with each token separated by a space. Use
null
for missing nodes. - The second line contains a single integer, the target value.
outputFormat
Print a single line containing the nodes along the path from the root to the target value, separated by spaces. If the target is not found, print an empty line.
## sample5 3 8 2 4 null 10
4
5 3 4