Using Depth First Search - O(n) Time and O(h) Space
The idea is to check the levelof both the given node values using depth first search. If their levels are same, then check if they are childrenof same or different nodes. If they havesameparent, then return false. else, return true.
C++
#include<iostream>usingnamespacestd;classNode{public:intdata;Node*left,*right;Node(intx){data=x;left=right=nullptr;}};// Recursive function to check if two Nodes are siblingsboolareSiblings(Node*root,inta,intb){// Base caseif(root==nullptr)returnfalse;if(root->left!=nullptr&&root->right!=nullptr&&root->left->data==a&&root->right->data==b)returntrue;if(root->left!=nullptr&&root->right!=nullptr&&root->left->data==b&&root->right->data==a)returntrue;returnareSiblings(root->left,a,b)||areSiblings(root->right,a,b);}// Recursive function to find level of Node with data = valueintlevel(Node*root,intvalue,intlev){// Base casesif(root==nullptr)return0;if(root->data==value)returnlev;// Return level if Node is present in left subtreeintl=level(root->left,value,lev+1);if(l!=0)returnl;// Else search in right subtreereturnlevel(root->right,value,lev+1);}// Returns true if a and b are cousins, otherwise falseboolareCousins(Node*root,inta,intb){// Cousins must be at the same level and have different parents.if(a==b)returnfalse;intaLevel=level(root,a,1);intbLevel=level(root,b,1);// If either node does not exist in the treeif(aLevel==0||bLevel==0)returnfalse;return(aLevel==bLevel&&!areSiblings(root,a,b));}intmain(){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(areCousins(root,a,b))cout<<"true\n";elsecout<<"false\n";return0;}
C
// C program to // check if two Nodes are Cousins#include<stdio.h>#include<stdlib.h>structNode{intdata;structNode*left,*right;};// Recursive function to check if two Nodes are siblingsintareSiblings(structNode*root,inta,intb){// Base caseif(root==NULL)return0;if(root->left!=NULL&&root->right!=NULL&&root->left->data==a&&root->right->data==b)return1;if(root->left!=NULL&&root->right!=NULL&&root->left->data==b&&root->right->data==a)return1;returnareSiblings(root->left,a,b)||areSiblings(root->right,a,b);}// Recursive function to find level of // Node with data = value in a binary treeintlevel(structNode*root,intvalue,intlev){// base casesif(root==NULL)return0;if(root->data==value)returnlev;// Return level if Node is // present in left subtreeintl=level(root->left,value,lev+1);if(l!=0)returnl;// Else search in right subtreereturnlevel(root->right,value,lev+1);}// Returns true if a and b are cousins, otherwise falseintareCousins(structNode*root,inta,intb){// 1. The two Nodes should be on // the same level in the binary tree.// 2. The two Nodes should not be siblings // (means that they should not // have the same parent Node).if(a==b)return0;intaLevel=level(root,a,1);intbLevel=level(root,b,1);// if a or b does not exist in the treeif(aLevel==0||bLevel==0)return0;if(aLevel==bLevel&&!areSiblings(root,a,b))return1;elsereturn0;}structNode*createNode(intx){structNode*newNode=(structNode*)malloc(sizeof(structNode));newNode->data=x;newNode->left=newNode->right=NULL;returnnewNode;}intmain(){structNode*root=createNode(1);root->left=createNode(2);root->right=createNode(3);root->left->left=createNode(4);root->right->right=createNode(5);inta=4,b=5;if(areCousins(root,a,b)){printf("true\n");}else{printf("false\n");}return0;}
Java
// Java program to // check if two Nodes are CousinsclassNode{intdata;Nodeleft,right;Node(intx){data=x;left=right=null;}}classGFG{// Recursive function to check if // two Nodes are siblingsstaticbooleanareSiblings(Noderoot,inta,intb){// Base caseif(root==null)returnfalse;if(root.left!=null&&root.right!=null&&root.left.data==a&&root.right.data==b)returntrue;if(root.left!=null&&root.right!=null&&root.left.data==b&&root.right.data==a)returntrue;returnareSiblings(root.left,a,b)||areSiblings(root.right,a,b);}// Recursive function to find level of Node with // data = value in a binary treestaticintlevel(Noderoot,intvalue,intlev){// base casesif(root==null)return0;if(root.data==value)returnlev;// Return level if Node is present in left subtreeintl=level(root.left,value,lev+1);if(l!=0)returnl;// Else search in right subtreereturnlevel(root.right,value,lev+1);}// Returns true if a and b are cousins, otherwise falsestaticbooleanareCousins(Noderoot,inta,intb){// 1. The two Nodes should be on the same // level in the binary tree.// 2. The two Nodes should not be siblings //(means that they should not have // the same parent Node).if(a==b)returnfalse;intaLevel=level(root,a,1);intbLevel=level(root,b,1);// if a or b does not exist in the treeif(aLevel==0||bLevel==0)returnfalse;returnaLevel==bLevel&&!areSiblings(root,a,b);}publicstaticvoidmain(String[]args){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(areCousins(root,a,b)){System.out.println("true");}else{System.out.println("false");}}}
Python
# Python program to check if two # nodes in a binary tree are cousinsclassNode:def__init__(self,x):self.data=xself.left=self.right=None# Recursive function to check # if two Nodes are siblingsdefareSiblings(root,a,b):# Base caseifrootisNone:returnFalseifroot.leftisnotNoneandroot.rightisnotNoneand \
root.left.data==aandroot.right.data==b:returnTrueifroot.leftisnotNoneandroot.rightisnotNoneand \
root.left.data==bandroot.right.data==a:returnTruereturnareSiblings(root.left,a,b)orareSiblings(root.right,a,b)# Recursive function to find level of Node with # data = value in a binary treedeflevel(root,value,lev):# base casesifrootisNone:return0ifroot.data==value:returnlev# Return level if Node is present in left subtreel=level(root.left,value,lev+1)ifl!=0:returnl# Else search in right subtreereturnlevel(root.right,value,lev+1)# Returns true if a and b are cousins, otherwise falsedefareCousins(root,a,b):# 1. The two Nodes should be on the same # level in the binary tree.# 2. The two Nodes should not be siblings # (means that they should not # have the same parent Node).ifa==b:returnFalseaLevel=level(root,a,1)bLevel=level(root,b,1)# if a or b does not exist in the treeifaLevel==0orbLevel==0:returnFalsereturnaLevel==bLevelandnotareSiblings(root,a,b)if__name__=="__main__":root=Node(1)root.left=Node(2)root.right=Node(3)root.left.left=Node(4)root.right.right=Node(5)a,b=4,5ifareCousins(root,a,b):print("true")else:print("false")
C#
// C# program to // check if two Nodes are CousinsusingSystem;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=right=null;}}classGFG{// Recursive function to check // if two Nodes are siblingsstaticboolareSiblings(Noderoot,inta,intb){// Base caseif(root==null)returnfalse;if(root.left!=null&&root.right!=null&&root.left.data==a&&root.right.data==b)returntrue;if(root.left!=null&&root.right!=null&&root.left.data==b&&root.right.data==a)returntrue;returnareSiblings(root.left,a,b)||areSiblings(root.right,a,b);}// Recursive function to find level of // Node with data = value in a binary treestaticintLevel(Noderoot,intvalue,intlev){// base casesif(root==null)return0;if(root.data==value)returnlev;// Return level if Node is present in left subtreeintl=Level(root.left,value,lev+1);if(l!=0)returnl;// Else search in right subtreereturnLevel(root.right,value,lev+1);}// Returns true if a and b are cousins, otherwise falsestaticboolareCousins(Noderoot,inta,intb){// 1. The two Nodes should be on the // same level in the binary tree.// 2. The two Nodes should not be // siblings (means that they should // not have the same parent Node).if(a==b)returnfalse;intaLevel=Level(root,a,1);intbLevel=Level(root,b,1);// if a or b does not exist in the treeif(aLevel==0||bLevel==0)returnfalse;returnaLevel==bLevel&&!areSiblings(root,a,b);}staticvoidMain(){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(areCousins(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=this.right=null;}}// Recursive function to check if two Nodes are siblingsfunctionareSiblings(root,a,b){// Base caseif(root==null)returnfalse;if(root.left!=null&&root.right!=null&&root.left.data===a&&root.right.data===b)returntrue;if(root.left!=null&&root.right!=null&&root.left.data===b&&root.right.data===a)returntrue;returnareSiblings(root.left,a,b)||areSiblings(root.right,a,b);}// Recursive function to find level of Node with // data = value in a binary treefunctionlevel(root,value,lev){// base casesif(root==null)return0;if(root.data===value)returnlev;// Return level if Node is present in left subtreeletl=level(root.left,value,lev+1);if(l!==0)returnl;// Else search in right subtreereturnlevel(root.right,value,lev+1);}// Returns true if a and b are cousins, otherwise falsefunctionareCousins(root,a,b){// 1. The two Nodes should be on the same level// in the binary tree.// 2. The two Nodes should not be siblings // (means that they should not have the same parent Node).if(a===b)returnfalse;letaLevel=level(root,a,1);letbLevel=level(root,b,1);// if a or b does not exist in the treeif(aLevel===0||bLevel===0)returnfalse;returnaLevel===bLevel&&!areSiblings(root,a,b);}letroot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.right.right=newNode(5);leta=4,b=5;if(areCousins(root,a,b)){console.log("true");}else{console.log("false");}
Output
true
Using Breadth-First Search - O(n) Time and O(n) Space
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 depthbefore moving deeper. If the two nodes are found at the same level and are not siblings, then we returntrue, indicating they are cousins. Otherwise, wereturnfalse, as this means they either do not share the same depth or are sibling.
Step-by-step implementation:
If the tree is empty or a == b, return false.
Perform a level-order traversal (BFS) using a queue.
For each level, initialize two boolean variables, aFound and bFound, to track whether a and b are present at that level.
Process all nodes in the current level. Update aFound or bFound if the current node matches a or b. If both children exist and their values are (a, b) or (b, a), return false since the nodes are siblings. Push the left and right children (if they exist) into the queue.
After processing the current level, return true if both aFound and bFound are true. Return false if exactly one of them is true.
If the traversal completes without returning, return false.
C++
#include<iostream>#include<queue>usingnamespacestd;// Structure of a binary tree nodeclassNode{public:intdata;Node*left,*right;Node(intx){data=x;left=right=nullptr;}};// Function to check if two nodes are cousinsboolareCousins(Node*root,inta,intb){// Empty tree or same node values cannot be cousinsif(root==nullptr||a==b)returnfalse;queue<Node*>q;q.push(root);while(!q.empty()){intsz=q.size();// Track whether a and b are present at the current levelboolaFound=false,bFound=false;while(sz--){Node*curr=q.front();q.pop();if(curr->data==a)aFound=true;if(curr->data==b)bFound=true;// If a and b have the same parent, they are siblingsif(curr->left&&curr->right){intleft=curr->left->data;intright=curr->right->data;if((left==a&&right==b)||(left==b&&right==a))returnfalse;}if(curr->left)q.push(curr->left);if(curr->right)q.push(curr->right);}// Both nodes found at the same levelif(aFound&&bFound)returntrue;// Only one node found at this levelif(aFound||bFound)returnfalse;}returnfalse;}intmain(){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(areCousins(root,a,b))cout<<"true\n";elsecout<<"false\n";return0;}
Java
importjava.util.LinkedList;importjava.util.Queue;// Structure of a binary tree nodeclassNode{intdata;Nodeleft,right;Node(intx){data=x;left=right=null;}}publicclassGFG{// Function to check if two nodes are cousinspublicstaticbooleanareCousins(Noderoot,inta,intb){// Empty tree or same node values cannot be cousinsif(root==null||a==b)returnfalse;Queue<Node>q=newLinkedList<>();q.add(root);while(!q.isEmpty()){intsz=q.size();// Track whether a and b are present at the current levelbooleanaFound=false,bFound=false;while(sz-->0){Nodecurr=q.poll();if(curr.data==a)aFound=true;if(curr.data==b)bFound=true;// If a and b have the same parent, they are siblingsif(curr.left!=null&&curr.right!=null){intleft=curr.left.data;intright=curr.right.data;if((left==a&&right==b)||(left==b&&right==a))returnfalse;}if(curr.left!=null)q.add(curr.left);if(curr.right!=null)q.add(curr.right);}// Both nodes found at the same levelif(aFound&&bFound)returntrue;// Only one node found at this levelif(aFound||bFound)returnfalse;}returnfalse;}publicstaticvoidmain(String[]args){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(areCousins(root,a,b))System.out.println("true");elseSystem.out.println("false");}}
Python
fromcollectionsimportdeque# Structure of a binary tree nodeclassNode:def__init__(self,x):self.data=xself.left=Noneself.right=None# Function to check if two nodes are cousinsdefareCousins(root,a,b):# Empty tree or same node values cannot be cousinsifnotrootora==b:returnFalsequeue=deque([root])whilequeue:sz=len(queue)# Track whether a and b are present at the current levelaFound=FalsebFound=Falsewhilesz>0:sz-=1curr=queue.popleft()ifcurr.data==a:aFound=Trueifcurr.data==b:bFound=True# If a and b have the same parent, they are siblingsifcurr.leftandcurr.right:left=curr.left.dataright=curr.right.dataif(left==aandright==b)or(left==bandright==a):returnFalseifcurr.left:queue.append(curr.left)ifcurr.right:queue.append(curr.right)# Both nodes found at the same levelifaFoundandbFound:returnTrue# Only one node found at this levelifaFoundorbFound:returnFalsereturnFalseif__name__=='__main__':root=Node(1)root.left=Node(2)root.right=Node(3)root.left.left=Node(4)root.right.right=Node(5)a=4b=5ifareCousins(root,a,b):print('true')else:print('false')
C#
usingSystem;usingSystem.Collections.Generic;// Structure of a binary tree nodepublicclassNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=right=null;}}publicclassGFG{// Function to check if two nodes are cousinspublicstaticboolareCousins(Noderoot,inta,intb){// Empty tree or same node values cannot be cousinsif(root==null||a==b)returnfalse;Queue<Node>q=newQueue<Node>();q.Enqueue(root);while(q.Count>0){intsz=q.Count;// Track whether a and b are present at the current levelboolaFound=false,bFound=false;while(sz-->0){Nodecurr=q.Dequeue();if(curr.data==a)aFound=true;if(curr.data==b)bFound=true;// If a and b have the same parent, they are siblingsif(curr.left!=null&&curr.right!=null){intleft=curr.left.data;intright=curr.right.data;if((left==a&&right==b)||(left==b&&right==a))returnfalse;}if(curr.left!=null)q.Enqueue(curr.left);if(curr.right!=null)q.Enqueue(curr.right);}// Both nodes found at the same levelif(aFound&&bFound)returntrue;// Only one node found at this levelif(aFound||bFound)returnfalse;}returnfalse;}publicstaticvoidMain(){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(areCousins(root,a,b))Console.WriteLine("true");elseConsole.WriteLine("false");}}
JavaScript
classNode{constructor(x){this.data=x;this.left=null;this.right=null;}}// Function to check if two nodes are cousinsfunctionareCousins(root,a,b){// Empty tree or same node values cannot be cousinsif(!root||a===b)returnfalse;letq=[root];while(q.length>0){letsz=q.length;// Track whether a and b are present at the current levelletaFound=false,bFound=false;while(sz-->0){letcurr=q.shift();if(curr.data===a)aFound=true;if(curr.data===b)bFound=true;// If a and b have the same parent, they are siblingsif(curr.left&&curr.right){letleft=curr.left.data;letright=curr.right.data;if((left===a&&right===b)||(left===b&&right===a))returnfalse;}if(curr.left)q.push(curr.left);if(curr.right)q.push(curr.right);}// Both nodes found at the same levelif(aFound&&bFound)returntrue;// Only one node found at this levelif(aFound||bFound)returnfalse;}returnfalse;}letroot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.right.right=newNode(5);leta=4,b=5;if(areCousins(root,a,b))console.log('true');elseconsole.log('false');