VOOZH about

URL: https://www.geeksforgeeks.org/dsa/print-nodes-distance-k-given-node-binary-tree/

⇱ Print all nodes at distance k from a given node - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Print all nodes at distance k from a given node

Last Updated : 23 Jul, 2025

Given a binary tree, a target node in the binary tree, and an integer value k, the task is to find all the nodes at a distance k from the given target node. No parent pointers are available.

Note:

  • You have to return the list in sorted order.
  • The tree will not contain duplicate values.

Examples:

Input: target = 2, k = 2

👁 Iterative-Postorder-Traversal

Output: 3
Explanation: Nodes at a distance 2 from the given target node 2 is 3.

Input: target = 3, k = 1

👁 Iterative-Postorder-Traversal-3

Output: 1 6 7
Explanation: Nodes at a distance 1 from the given target node 3 are 1 , 6 & 7.

[Expected Approach - 1] Using Recursion - O(nlogn) Time and O(h) Space

The idea is to traverse the binary tree using recursion and find the target node. Find all the nodes in the left and right subtree of target node that are at a distance k. Also for all the nodes in the path of target node, find all the nodes in the opposite subtree that are at the distance of (k - distance of target node).

Below is the implementation of the above approach:


Output
1 24 

Time Complexity: O(nlogn), for sorting the result.
Auxiliary Space: O(h), where h is the height of the tree.

[Expected Approach - 2] Using DFS with Parent Pointers - O(nlogn) Time and O(n) Space:

The idea is to recursively find the target node and map each node to its parent node. Then, starting from the target node, apply depth first search (DFS) to find all the nodes at distance k from the target node.

Below is the implementation of the above approach:


Output
1 24 

Time Complexity: O(nlogn), for sorting the result.
Space Complexity: O(h), where h is the height of the tree.

Related article:

Comment