Find Every Profile Exactly K Hops From a Target in a Tree

Last updated: November 29, 2026

Quick Overview

Given a binary tree, a target node, and an integer k, return the values of all nodes at distance exactly k edges from the target, moving through parents as well as children.

Meta
Coding & Algorithms
Software Engineer
Meta
November 29, 2026
Software Engineer
Onsite
Coding & Algorithms
Medium

0

0

0 solved


Given a binary tree, a target node, and an integer k, return the values of all nodes at distance exactly k edges from the target, moving through parents as well as children.

A Meta onsite favorite because a tree has to be treated as an undirected graph. The interviewer checks that you build parent links (or an adjacency map) and run BFS from the target with a visited set.

What the Interviewer Expects
  • Recognize that distance can go up through parents
  • Record parent pointers with one traversal
  • BFS from the target for k levels
  • Use a visited set to avoid bouncing back
  • Handle k = 0 and k larger than the tree height
Key Topics to Cover
Binary trees
Breadth-first search
Parent pointers
Graph conversion
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
  • Can you solve it without storing parent pointers, using distances returned from DFS?
  • How would you answer many (target, k) queries efficiently?
  • What changes for an n-ary tree?
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice DSA Problems
Sample Answer
Requirements

Inputs are the tree root, a node reference target inside the tree, and k >= 0. Return the values of nodes whose shortest path distance to target is k, in any order. Values are unique....

High-Level Design

First traverse the tree once to map each node to its parent. Now each node has up to three neighbors: left, right, and parent. Run BFS from target, one layer at a time, marking nodes visited. After ...


Submit Your Answer
Markdown supported