You are given the root of a binary tree, the value of a target node, and an integer k. Your task is to return all node values that are exactly k edges away from the target node.
A node can be reached by moving:
Return all nodes whose shortest distance from the target node is exactly k.
Input: root = [3,5,1,6,2,0,8,null,null,7,4], target = 5, k = 2
Output: [7,4,1]
Explanation: The nodes 7, 4, and 1 are exactly 2 edges away from node 5.
Input: root = [1], target = 1, k = 0
Output: [1]
Explanation: The target node is at distance 0 from itself.
Input: root = [1,2,3], target = 2, k = 2
Output: [3]
Explanation: Node 3 is exactly 2 edges away from node 2.
Approach, complexity and clean code in every language. Sign in to unlock the editorial.
Your submissions, results and runtime history live here. Sign in to start your streak.
1 2 3 4 5 6 7 2 2
4 5 3
10 5 15 2 7 12 20 5 2
15 7
8 4 10 2 6 9 12 4 1
2 6 8