All Tree Nodes Exactly K Hops Away From a Target Node

Last updated: November 29, 2026

Quick Overview

Given the root of a binary tree, a target node, and an integer k, return the values of all nodes whose distance from the target is exactly k edges, moving up or down the tree.

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

0

0

0 solved


Given the root of a binary tree, a target node, and an integer k, return the values of all nodes whose distance from the target is exactly k edges, moving up or down the tree.

A Google onsite favorite because it forces you to treat a tree as an undirected graph. The interviewer is checking that you add parent links (or an adjacency map) and then run a BFS that can move up as well as down.

What the Interviewer Expects
  • Record parent pointers with one traversal
  • Run BFS from the target over children and parent
  • Use a visited set so you do not bounce back
  • Stop at depth k and return that level
  • Offer a single-pass DFS alternative
Key Topics to Cover
binary tree
BFS
parent pointers
tree as graph
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
  • Do it without extra parent storage in one DFS pass.
  • Return nodes within distance k, not exactly k.
  • Answer many (target, k) queries quickly.
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
  • Input: root, target (a node in the tree), k >= 0.
  • Distance counts edges along the unique tree path.
  • Output: list of values, any order....
High-Level Design

Paths can go up through ancestors and back down other branches, so a plain top-down traversal is not enough. First DFS the tree to record parent[node]. Now every node has up to 3 neighbors (left, ri...


Submit Your Answer
Markdown supported