#863

All Nodes Distance K in Binary Tree

pupil · 590 · lc medium +29 · verified · 67.5% accepted · 12,075 likes · top 74%

Description

Given the root of a binary tree, a target node target, and an integer k, return a list of values of all nodes that are exactly distance k from target.

The result may be returned in any order.

Example 1:

Input: root = [3,5,1,6,2,0,8,null,null,7,4], target = 5, k = 2
Output: [7,4,1]
Explanation: The nodes that are a distance 2 from the target node (with value 5) have values 7, 4, and 1.

Example 2:

Input: root = [1], target = 1, k = 3
Output: []

Code

1
2
3
4
5
6
7
8
9
10