Skip to content

All Nodes Distance K in Binary Tree

MediumTrees
Decode it first. Clues, constraints, pattern and plan before any code.

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.

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

Constraints

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