Given a binary tree (having distinct node values) root and two node values. The task is to check whether the two nodes with values a and b are cousins. Note: Two nodes of a binary tree are cousins if they have the same depth with different parents.
The idea is to check the level of both the given node values using depth first search. If their levels are same, then check if they are children of same or different nodes. If they have same parent, then return false. else, return true.
Below is the implementation of the above approach.
Output
True
Time Complexity O(n), where n are the number of nodes in binary tree. Auxiliary complexity: O(h), where h is the height of the tree.
In a depth-first search (DFS) approach to check if two nodes are cousins, we traverse the tree three times, resulting in a time complexity O(3n).
Using Breadth-First Search :
The idea is to use a queue to traverse the tree in a level-order manner. This allows us to explore all nodes at a given depth before moving deeper. If the two nodes are found at the same level and are not siblings, then we return true, indicating they are cousins. Otherwise, we return false, as this means they either do not share the same depth or are sibling. Please Refer to Check if two nodes are cousins in a Binary Tree using BFS for implementation.
Time Complexity O(n), where n are the number of nodes in binary tree. Auxiliary Space: O(n), if the tree is completely unbalanced, the maximum size of the queue can grow to O(n).