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
- Print cousins of a given node in Binary Tree | Single Traversal
- Check if two nodes in a Binary Tree are siblings
- 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
- Sink even nodes in Binary Tree
- XOR of path between any two nodes in a Binary Tree
- Sink Odd nodes in Binary Tree
- Sum of all the Boundary Nodes of a Binary Tree
- Sum of nodes in top view of binary tree
- Sum of nodes in the right view of the given binary tree
- Sum of all leaf nodes of 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 firstname.lastname@example.org. 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.