Print all nodes at a distance of K in BT

Binary Trees FAQs Hard

Given the root of a binary tree, the value of a target node target, and an integer k. Return an array of the values of all nodes that have a distance k from the target node.


The answer can be returned in any order (N represents null).

Examples:

Input : root = [3, 5, 1, 6, 2, 0, 8, N, N, 7, 4] , target = 5, k = 2

Output : [1, 4, 7]

Explanation : The nodes that are a distance 2 from the target node (with value 5) have values 7, 4, and 1.

Input : root = [3, 5, 1, 6, 2, 0, 8, N, N, 7, 4] , target = 5, k = 3

Output : [0, 8]

Explanation : The nodes that are a distance 3 from the target node (with value 5) have values 0, 8.

Input : root = [5, 1, 2, 8, 10, 4, 5, null, 6], target = 10, k = 3

Constraints

  • 1 <= Number of Nodes <= 103
  • -104 <= Node.val <= 104
  • All the values Node.val are unique.
  • target is the value of one of the nodes in the tree
  • 0 <= k <= 103

Hints

  • Use DFS or BFS to build a graph (adjacency list) where: Each node points to its left and right children. Each node points to its parent (establishing bidirectional links).
  • Start from the target node and use BFS to traverse exactly k levels. Keep track of visited nodes to avoid cycles. Once BFS reaches level k, store all nodes and return them.

Company Tags

Snowflake Walmart MongoDB Activision Blizzard HashiCorp Etsy Riot Games Rakuten Teladoc Health Cloudflare Broadcom Philips Healthcare Pinterest Optum GE Healthcare Shopify Bloomberg Roche Intel Twilio Instacart Cerner Uber Swiggy Bungie Google Microsoft Amazon Meta Apple Netflix Adobe