905. All Nodes Distance K in Binary Tree

MediumTreesBinary TreeBFSGraph

Given the root of a binary tree, a target node value, and an integer k, return the values of all nodes that are at distance exactly k from the target node, where distance is the number of edges in the tree treated as an undirected graph. Return the values sorted in ascending order. Node values are unique. The input gives a level-order tree array and 'target k' separated by ' | '.

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

Output: Array — node values at distance k, sorted.

Examples

Example 1
Input: [3,5,1,6,2,0,8,null,null,7,4] | 5 2
Output: [1,4,7]
Explanation: Nodes two edges from node 5.
Example 2
Input: [1,2,3] | 1 1
Output: [2,3]
Explanation: Both children.
Example 3
Input: [1] | 1 0
Output: [1]
Explanation: The target itself.

Constraints

Asked by

MetaAmazonMicrosoftFlipkartOracleGoogle
Solve this problem in the editor →