Determine if given two nodes are cousins of each other

Given a binary tree, determine if two given nodes are cousins of each other or not. 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


level order traversal

(4, 6), (4, 7), (5, 6) and (5, 7) are cousins of each other
(2, 3), (4, 5), (6, 7), (4, 3), etc are not cousins of each other



The idea is to search for given nodes in binary tree by doing an in-order traversal of the tree and store their level and parent node. Once both nodes are found, if they are present at same level and have different parents, they are cousins of each other. If their level are different or they are sibling of each other, they cannot be cousins.

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.

1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)

Thanks for reading.

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂

Leave a Reply

Notify of