VOOZH about

URL: https://www.geeksforgeeks.org/dsa/print-cousins-of-a-given-node-in-binary-tree/

⇱ Print cousins of a given node in Binary Tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Print cousins of a given node in Binary Tree

Last Updated : 23 Jul, 2025

Given a binary tree and a node, print all cousins of given node. Note that siblings should not be printed.
Example: 
 

Input : root of below tree 
 1
 / \
 2 3
 / \ / \
 4 5 6 7
 and pointer to a node say 5.

Output : 6, 7

The idea to first find level of given node using the approach discussed here. Once we have found level, we can print all nodes at a given level using the approach discussed here. The only thing to take care of is, sibling should not be printed. To handle this, we change the printing function to first check for sibling and print node only if it is not sibling.

Below is the implementation of above idea. 


Output
6 7

Time Complexity : O(n)
Auxiliary Space: O(n) due to recursion.

Another Approach(Iterative Approach):
An efficient and easy to implement approach by level order traversal using queue.
Follow the below steps to solve this problem:
1) First perform level order traversal using queue.
2) Check for each node that its left or right child is match with target(given) node then don't insert its childrens and mark found variable to true but insert other nodes of just upper nodes in queue.
3) After insert all the nodes print them and return.

Below is the implementation of above approach:


Output
6 7 

Time Complexity: O(N) where N is the number of nodes in a given binary tree.
Auxiliary Space: O(N) due to queue data structure.

Can we solve this problem using single traversal? Please refer below article 
Print cousins of a given node in Binary Tree | Single Traversal

Comment
Article Tags:
Article Tags: