#K58152. Find All Nodes at Distance K in a Binary Tree
Find All Nodes at Distance K in a Binary Tree
Find All Nodes at Distance K in a Binary Tree
Given a binary tree, a target node value, and an integer K, find all nodes in the tree that are exactly at distance K from the target node. The tree is provided in level-order format where the string "null" represents a missing node.
In this problem, consider each edge of the tree as bidirectional. That is, the binary tree can be viewed as an undirected graph. You are required to output the node values (sorted in ascending order) that are at the specified distance from the target node.
Note: If the target node occurs in the tree, it is guaranteed to be unique. The distance between two nodes is defined as the number of edges in the shortest path connecting them.
The mathematical definition of the distance can be expressed in \(\LaTeX\) as:
[ d(u,v)=\min{\text{number of edges on any path connecting } u \text{ and } v}]
inputFormat
The input is given via standard input (stdin) and consists of three parts:
- First line: A space-separated string representing the level-order traversal of the binary tree. Use "null" to indicate a missing node.
- Second line: An integer representing the target node's value.
- Third line: An integer K representing the required distance from the target node.
outputFormat
Output the values of all nodes at distance exactly K from the target node. The node values should be printed in ascending order, separated by a single space.
## sample3 5 1 6 2 null 9 null null 7 4
5
2
1 4 7