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.
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.
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;}};// Recursive function to check if two Nodes are siblingsboolisSibling(Node*root,inta,intb){// Base caseif(root==NULL)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;returnisSibling(root->left,a,b)||isSibling(root->right,a,b);}// Recursive function to find level of Node with data = value in a// binary treeintlevel(Node*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 falseboolisCousins(Node*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)returnfalse;intaLevel=level(root,a,1);intbLevel=level(root,b,1);// if a or b does not exists in the treeif(aLevel==0||bLevel==0)returnfalse;if(aLevel==bLevel&&!isSibling(root,a,b))returntrue;elsereturnfalse;}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;}
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 siblingsintisSibling(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;returnisSibling(root->left,a,b)||isSibling(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 falseintisCousins(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&&!isSibling(root,a,b))return1;elsereturn0;}structNode*createNode(intx){structNode*newNode=(structNode*)malloc(sizeof(structNode));newNode->data=x;newNode->left=newNode->right=NULL;returnnewNode;}intmain(){// create hard coded tree// 1// / \ // 2 3// / \ // 5 4 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(isCousins(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 siblingsstaticbooleanisSibling(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;returnisSibling(root.left,a,b)||isSibling(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 falsestaticbooleanisCousins(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&&!isSibling(root,a,b);}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 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 siblingsdefisSibling(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:returnTruereturnisSibling(root.left,a,b)orisSibling(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 falsedefisCousins(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==bLevelandnotisSibling(root,a,b)if__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,b=4,5ifisCousins(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 siblingsstaticboolIsSibling(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;returnIsSibling(root.left,a,b)||IsSibling(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 falsestaticboolIsCousins(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&&!IsSibling(root,a,b);}staticvoidMain(){// 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=this.right=null;}}// Recursive function to check if two Nodes are siblingsfunctionisSibling(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;returnisSibling(root.left,a,b)||isSibling(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 falsefunctionisCousins(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&&!isSibling(root,a,b);}// create hard coded tree// 1// / \ // 2 3// / \// 5 4 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(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 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).