VOOZH about

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

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


  • Courses
  • Tutorials
  • Interview Prep

Print cousins of a given node in Binary Tree | Single Traversal

Last Updated : 11 Jul, 2025

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

Examples: 

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

Output : 6, 7
Recommended Practice

Note that it is the same problem as given at Print cousins of a given node in Binary Tree which consists of two traversals recursively. In this post, a single level traversal approach is discussed.
The idea is to go for level order traversal of the tree, as the cousins and siblings of a node can be found in its level order traversal. Run the traversal till the level containing the node is not found, and if found, print the given level.

How to print the cousin nodes instead of siblings and how to get the nodes of that level in the queue? 
During the level order, when for the parent node, if parent->left == Node_to_find, or parent->right == Node_to_find, then the children of this parent must not be pushed into the queue (as one is the node and other will be its sibling). Push the remaining nodes at the same level in the queue and then exit the loop. The current queue will have the nodes at the next level (the level of the node being searched, except the node and its sibling). Now, print the queue.

Following is the implementation of the above algorithm. 


Output
Node not found
Cousin Nodes : None
Cousin Nodes : None
Cousin Nodes : None
Cousin Nodes : 6 7 

Time Complexity : This is a single level order traversal, hence time complexity = O(n), and Auxiliary space = O(n) (See this).

Comment
Article Tags:
Article Tags: