← DiffPush

All Nodes at Distance K

DiffPush Tier Binary Trees · Hard O(n) · O(n)

The Radio Check Distress Sweep

A mountain rescue network is laid out as a binary tree of relay posts. When a post sends a distress ping, dispatch must name every relay exactly k hops away — counting along child links and the parent link alike — so neighbouring teams can be paged at once. Hops shorter or longer than k stay silent, and the call order doesn't matter.

Input: A binary tree as a level-order array (null marks a missing child), an integer target — the value of the origin post — and an integer k, the exact hop distance.

Output: Return the values of all nodes at exactly distance k from the target, in any order.

Constraints

Examples

Example 1

Input: {"tree":[3,5,1,6,2,0,8,null,null,7,4],"target":5,"k":2}
Output: [1,4,7]
Two hops from 5 reach its parent 3's other child 1, and 5's grandchildren 7 and 4.

Example 2

Input: {"tree":[3,5,1,6,2,0,8,null,null,7,4],"target":5,"k":3}
Output: [0,8]
Three hops from 5 lands on the root 3's two children 0 and 8.

Solve this in your browser →

Also on LeetCode ↗