865. Print Nodes at Distance K from Root

EasyTreesBinary TreeBFS

Given the root of a binary tree and an integer k, return the values of all nodes at distance k from the root (the root is at distance 0), in left-to-right order. Return an empty array if no node is at that distance. The input gives a level-order tree array and k separated by ' | '.

Input: A level-order tree array and k, separated by ' | '.

Output: Array — node values at distance k.

Examples

Example 1
Input: [1,2,3,4,5,null,7] | 2
Output: [4,5,7]
Explanation: Nodes two levels below the root.
Example 2
Input: [1,2,3] | 1
Output: [2,3]
Explanation: Children of the root.
Example 3
Input: [1] | 0
Output: [1]
Explanation: Root itself.

Constraints

Asked by

TCSInfosysWiproCognizantCapgemini
Solve this problem in the editor →