#K55077. Nodes at Distance K in a Binary Tree
Nodes at Distance K in a Binary Tree
Nodes at Distance K in a Binary Tree
You are given a binary tree and two integers target and K. Your task is to find all the node values in the tree that are exactly K edges away from the node whose value is equal to target.
The binary tree is provided as a level order traversal where the token null
represents a missing node. The second line of input contains two integers: the target node's value and the distance K.
Note: The answer can be returned in any order, but your program must output the node values separated by a single space. If no nodes exist at the required distance, output an empty line.
Example 1:
Input: 3 5 1 6 2 0 8 null null 7 4 5 2</p>Output: 7 4 1
Example 2:
Input: 1 2 3 4 5 2 1</p>Output: 4 5 1
inputFormat
The first line contains the level order traversal of the binary tree. Each token is either an integer or the string null
(without quotes) representing a missing node. The tokens are separated by spaces.
The second line contains two integers: target
and K
, separated by a space.
outputFormat
Output a single line containing the values of all nodes that are at distance K
from the target node, separated by a single space. If no nodes exist at that distance, output an empty line.
3 5 1 6 2 0 8 null null 7 4
5 2
7 4 1