157. All Nodes Distance K in Binary Tree

Medium · Binary Tree

Given a binary tree, a target node value, and a distance k, find all node values that are exactly k edges away from the target node. The target node itself is 0 edges away. You can move in any direction (up to parent, down to children). Return the result as an ascending sorted array.

Input format: [arr, targetVal, k] where arr is a level-order serialization of the binary tree (with null for missing nodes), targetVal is the value of the target node, and k is the distance. Output: an ascending sorted array of all node values exactly k edges from the target.

Examples

Example 1
Input: [[3,5,1,6,2,0,8,null,null,7,4], 5, 2]
Output: [1,4,7]
Explanation: Two edges from node 5
Example 2
Input: [[1], 1, 3]
Output: []
Explanation: No nodes that far

Constraints