Skip to content
Decoder

All Nodes Distance K in Binary Tree

Medium

Problem

Given the root of a binary tree, the value target of one of its nodes, and an integer k, return the values of all nodes exactly `k` edges away from the target node. Distance can go up through parents as well as down, so the answer may include nodes in a completely different branch. Return the values in any order.

Trees in the examples are written in level order (top to bottom, left to right), with null for a missing child, the same way the tests build them.

Example 1

Input
root = [3, 5, 1, 6, 2, 0, 8, null, null, 7, 4], target = 5, k = 2
Output
[7, 4, 1]

Example 2

Input
root = [3, 5, 1, 6, 2, 0, 8, null, null, 7, 4], target = 5, k = 0
Output
[5]

Example 3

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

Constraints

  • 1 <= number of nodes <= 500
  • 0 <= Node.val <= 500
  • All values are unique, and target is in the tree.
  • 0 <= k <= 1000

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.