Meta OA Interview Question: Find All Nodes at Distance K from a Target Node in a Binary Tree

16 Views
No Comments

Given a binary tree (pointer to the root), a target node anywhere in the tree, and an integer value K, return a list of the values of all the nodes that have a distance K from the target node. The order of the list does not matter.

Example:

print_tree(root, 3)
find_at_distance(root, 3, 2)
[2, 6, 7, 8]

This problem asks for all nodes exactly K edges away from a target in a binary tree. A standard solution is to first record parent links with DFS, then run BFS from the target while tracking visited nodes to avoid revisiting the same edge in both directions. This allows the search to move downward into children and upward to the parent, which is necessary because nodes at distance K may lie on either side of the target. The example with target 3 and K = 2 returns [2, 6, 7, 8].

END
 0