Given a binary tree and the two nodes say ‘a’ and ‘b’, determine whether two given nodes are cousins of each other or not.
Two nodes are cousins of each other if they are at same level and have different parents.
6 / \ 3 5 / \ / \ 7 8 1 3 Say two node be 7 and 1, result is TRUE. Say two nodes are 3 and 5, result is FALSE. Say two nodes are 7 and 5, result is FALSE.
A solution in Set-1 that finds whether given nodes are cousins or not by performing three traversals of binary tree has been discussed. The problem can be solved by performing level order traversal. The idea is to use a queue to perform level order traversal, in which each queue element is a pair of node and parent of that node. For each node visited in level order traversal, check if that node is either first given node or second given node. If any node is found store parent of that node. While performing level order traversal, one level is traversed at a time. If both nodes are found in given level, then their parent values are compared to check if they are siblings or not. If one node is found in given level and another is not found, then given nodes are not cousins.
Below is the implementation of above approach:
Time Complexity: O(n)
Auxiliary Space: O(n)
- Check if two nodes are cousins in a Binary Tree
- Sum of cousins of a given node in a Binary Tree
- Print cousins of a given node in Binary Tree
- Check if two nodes in a Binary Tree are siblings
- Print cousins of a given node in Binary Tree | Single Traversal
- Check sum of Covered and Uncovered nodes of Binary Tree
- Check whether a binary tree is a full binary tree or not | Iterative Approach
- Sum of all nodes in a binary tree
- Sum of nodes in top view of binary tree
- XOR of path between any two nodes in a Binary Tree
- Sum of all the Boundary Nodes of a Binary Tree
- Product of all nodes in a Binary Tree
- Sum of all leaf nodes of binary tree
- Sink Odd nodes in Binary Tree
- Print path between any two nodes in a Binary Tree
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.