VOOZH about

URL: https://www.geeksforgeeks.org/dsa/check-if-two-nodes-are-cousins-in-a-binary-tree-set-2/

⇱ Check if two nodes are cousins in a Binary Tree using BFS - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Check if two nodes are cousins in a Binary Tree using BFS

Last Updated : 11 Jul, 2025

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.

Example:

Input: a = 5, b = 4

👁 12-example

Output: True
Explanation: Node with the values 5 and 4 are on the same level with different parents.

Input: a = 4, b = 5

👁 11-example

Output: False
Explanation: Node with the values 5 and 4 are on the same level with same parent.

Approach:

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.

Step-by-step implementation:

  • Initialize two boolean variables. Lets say aFound and bFound (initially set to false).
  • Push the root node into a queue and follow while queue is not empty:
    • Calculate the size of the queue, say 's'. Pop 's' nodes in one iteration. This way, we will traverse the tree in level order.
    • Pop the node. If the node has value equal to a, then set aFound=true. If its value is equal to b, set bFound=true. To check that a and b are siblings or not, check if the given node has two children nodes. If it has two children and they are equal to a and b or b and a, then return false. Otherwise, push the left and right child nodes into the queue.
    • After popping 's' elements, check the values of aFound and bFound. If both of them are true, then it means that both these nodes were found at the same level, and return true. If one of them is true, then return false as their level is different. If both are false, then continue the steps.

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 Space: O(n), if the tree is completely unbalanced, the maximum size of the queue can grow to O(n).

Please Refer to Check if two nodes are cousins in a Binary Tree to solve using Depth First Search.

Comment