Print cousins of given node in a binary tree

Given a binary tree, print all cousins of a given node. Two nodes of binary tree are cousins of each other only if they have different parents but they have same level.

 

For example, consider below tree

binary-tree


6, 7 are cousins of node 4 or 5
4, 5 are cousins of node 6 or 7

 


 

The idea is to find level of given node in binary tree by doing a pre-order traversal of the tree. Once the level is found, we print all nodes present in that level which is not sibling of given node or the node itself.

 
C++ implementation –
 

Download   Run Complete Code

 
The time complexity of above solution is O(n) and need O(h) extra space for the call stack where h is the height of the tree.
 

Thanks for reading.
 




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz