All Nodes Distance K in Binary Tree

MediumTreesbfs

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

You are given the root of a binary tree whose node values are all **distinct**, the value target of one node in the tree, and an integer k. Return the values of every node that is exactly k edges away from the target node. Distance is measured along tree edges in either direction, so the path may go up through parents and back down another branch. The values may be returned in **any order**. If no node is at that distance, return []. When k = 0, the answer is just [target]. Treat the tree as an undirected graph (for example by recording each node's parent) and run a breadth-first search from the target, for O(n) time.

Examples

Input: root = [3,5,1,6,2,0,8,null,null,7,4], target = 5, k = 2
Output: [7,4,1]
7 and 4 are grandchildren of 5; 1 is reached by going up to 3 and down to 1.
Input: root = [1], target = 1, k = 3
Output: []
The tree has no node three edges away.

Constraints

  • 1 <= number of nodes <= 500
  • 0 <= Node.val <= 500
  • All values are distinct
  • `target` is the value of a node in the tree
  • 0 <= k <= 1000

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More bfs problems