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
Output: True Explanation: Node with the values 5 and 4 are on the same level with different parents.
Input: a = 4, b = 5
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:
C++
// C++ program to // check if two Nodes are Cousins#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left,*right;Node(intx){data=x;left=right=nullptr;}};// Funtion to check if two nodes are cousinsboolisCousins(Node*root,inta,intb){// base caseif(root==nullptr)returnfalse;// return false if a and b are equalif(a==b)returnfalse;queue<Node*>q;// Push the root node into queueq.push(root);// variables to check if a and b are found yet.boolaFound=false,bFound=false;while(!q.empty()){ints=q.size();// To simulate level order traversal,// only traverse the first s nodes in// the queue.while(s--){Node*curr=q.front();q.pop();if(curr->data==a)aFound=true;if(curr->data==b){bFound=true;}// if a and b are children to the same node, // then return false.if(curr->left!=nullptr&&curr->right!=nullptr&&((curr->left->data==a&&curr->right->data==b)||(curr->left->data==b&&curr->right->data==a)))returnfalse;// push left node into queue if(curr->left!=nullptr)q.push(curr->left);// Push right node into queue. if(curr->right!=nullptr)q.push(curr->right);}// After iteration of one level, following needs to // be checked// if both a and b are found,// return true.if(aFound&&bFound)returntrue;// if one of a or b is found,// return false.if(aFound||bFound)returnfalse;}returnfalse;}intmain(){// create hard coded tree// 1// / \ // 2 3// / \ // 5 4 Node*root=newNode(1);root->left=newNode(2);root->right=newNode(3);root->left->left=newNode(4);root->right->right=newNode(5);inta=4,b=5;if(isCousins(root,a,b)){cout<<"True"<<endl;}else{cout<<"False"<<endl;}return0;}
Java
// Java program to // check if two Nodes are Cousinsimportjava.util.LinkedList;importjava.util.Queue;classNode{intdata;Nodeleft,right;Node(intx){data=x;left=right=null;}}// Function to check if two nodes are cousinsclassGfG{staticbooleanisCousins(Noderoot,inta,intb){// base caseif(root==null)returnfalse;// return false if a and b are equalif(a==b)returnfalse;Queue<Node>q=newLinkedList<>();// Push the root node into queueq.add(root);// variables to check if a and b are found yet.booleanaFound=false,bFound=false;while(!q.isEmpty()){ints=q.size();// To simulate level order traversal,// only traverse the first s nodes in// the queue.for(inti=0;i<s;i++){Nodecurr=q.poll();if(curr.data==a)aFound=true;if(curr.data==b){bFound=true;}// if a and b are children to the same node, // then return false.if(curr.left!=null&&curr.right!=null&&((curr.left.data==a&&curr.right.data==b)||(curr.left.data==b&&curr.right.data==a))){returnfalse;}// push left node into queue if(curr.left!=null)q.add(curr.left);// Push right node into queue. if(curr.right!=null)q.add(curr.right);}// After iteration of one level, following needs to // be checked// if both a and b are found,// return true.if(aFound&&bFound)returntrue;// if one of a or b is found,// return false.if(aFound||bFound)returnfalse;}returnfalse;}publicstaticvoidmain(String[]args){// create hard coded tree// 1// / \ // 2 3// / \// 5 4 Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.right.right=newNode(5);inta=4,b=5;if(isCousins(root,a,b)){System.out.println("True");}else{System.out.println("False");}}}
Python
# Python program to # check if two Nodes are CousinsfromcollectionsimportdequeclassNode:def__init__(self,x):self.data=xself.left=Noneself.right=None# Function to check if two nodes are cousinsdefisCousins(root,a,b):# base caseifnotroot:returnFalse# return false if a and b are equalifa==b:returnFalsequeue=deque()# Push the root node into queuequeue.append(root)# variables to check if a and b are found yet.aFound=FalsebFound=Falsewhilequeue:s=len(queue)# To simulate level order traversal,# only traverse the first s nodes in# the queue.for_inrange(s):curr=queue.popleft()ifcurr.data==a:aFound=Trueifcurr.data==b:bFound=True# if a and b are children to the same node, # then return False.ifcurr.leftandcurr.rightand \
((curr.left.data==aandcurr.right.data==b)or(curr.left.data==bandcurr.right.data==a)):returnFalse# push left node into queue ifcurr.left:queue.append(curr.left)# Push right node into queue. ifcurr.right:queue.append(curr.right)# After iteration of one level, following needs to # be checked# if both a and b are found,# return True.ifaFoundandbFound:returnTrue# if one of a or b is found,# return False.ifaFoundorbFound:returnFalsereturnFalseif__name__=="__main__":# create hard coded tree# 1# / \ # 2 3# / \# 5 4 root=Node(1)root.left=Node(2)root.right=Node(3)root.left.left=Node(4)root.right.right=Node(5)a=4b=5ifisCousins(root,a,b):print("True")else:print("False")
C#
// C# program to // check if two Nodes are CousinsusingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=right=null;}}classGfG{// Function to check if two nodes are cousinsstaticboolIsCousins(Noderoot,inta,intb){// base caseif(root==null)returnfalse;// return false if a and b are equalif(a==b)returnfalse;Queue<Node>q=newQueue<Node>();// Push the root node into queueq.Enqueue(root);// variables to check if a and b are found yet.boolaFound=false,bFound=false;while(q.Count>0){ints=q.Count;// To simulate level order traversal,// only traverse the first s nodes in// the queue.for(inti=0;i<s;i++){Nodecurr=q.Dequeue();if(curr.data==a)aFound=true;if(curr.data==b){bFound=true;}// if a and b are children to the same node, // then return false.if(curr.left!=null&&curr.right!=null&&((curr.left.data==a&&curr.right.data==b)||(curr.left.data==b&&curr.right.data==a))){returnfalse;}// push left node into queue if(curr.left!=null)q.Enqueue(curr.left);// Push right node into queue. if(curr.right!=null)q.Enqueue(curr.right);}// After iteration of one level, following needs to // be checked// if both a and b are found,// return true.if(aFound&&bFound)returntrue;// if one of a or b is found,// return false.if(aFound||bFound)returnfalse;}returnfalse;}staticvoidMain(string[]args){// create hard coded tree// 1// / \ // 2 3// / \// 5 4 Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.right.right=newNode(5);inta=4,b=5;if(IsCousins(root,a,b)){Console.WriteLine("True");}else{Console.WriteLine("False");}}}
JavaScript
// JavaScript program to // check if two Nodes are CousinsclassNode{constructor(x){this.data=x;this.left=null;this.right=null;}}// Function to check if two nodes are cousinsfunctionisCousins(root,a,b){// base caseif(!root)returnfalse;// return false if a and b are equalif(a==b)returnfalse;constqueue=[];// Push the root node into queuequeue.push(root);// variables to check if a and b are found yet.letaFound=false,bFound=false;while(queue.length>0){constsize=queue.length;// To simulate level order traversal,// only traverse the first size nodes in// the queue.for(leti=0;i<size;i++){constcurr=queue.shift();if(curr.data===a)aFound=true;if(curr.data===b){bFound=true;}// if a and b are children to the same node, // then return false.if(curr.left!==null&&curr.right!==null&&((curr.left.data===a&&curr.right.data===b)||(curr.left.data===b&&curr.right.data===a))){returnfalse;}// push left node into queue if(curr.left!==null)queue.push(curr.left);// Push right node into queue. if(curr.right!==null)queue.push(curr.right);}// After iteration of one level, following needs to // be checked// if both a and b are found,// return true.if(aFound&&bFound)returntrue;// if one of a or b is found,// return false.if(aFound||bFound)returnfalse;}returnfalse;}// create hard coded tree// 1// / \ // 2 3// / \// 5 4 constroot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.right.right=newNode(5);consta=4,b=5;if(isCousins(root,a,b)){console.log("True");}else{console.log("False");}
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).