All Nodes Distance K in Binary Tree
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 neededProblem
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
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.