Given a binary tree and the two nodes say ‘a’ and ‘b’, determine whether two given nodes are cousins of each other or not.
Two nodes are cousins of each other if they are at same level and have different parents.
Example:
6
/ \
3 5
/ \ / \
7 8 1 3
Say two node be 7 and 1, result is TRUE.
Say two nodes are 3 and 5, result is FALSE.
Say two nodes are 7 and 5, result is FALSE.
A solution in Set-1 that finds whether given nodes are cousins or not by performing three traversals of binary tree has been discussed. The problem can be solved by performing level order traversal. The idea is to use a queue to perform level order traversal, in which each queue element is a pair of node and parent of that node. For each node visited in level order traversal, check if that node is either first given node or second given node. If any node is found store parent of that node. While performing level order traversal, one level is traversed at a time. If both nodes are found in given level, then their parent values are compared to check if they are siblings or not. If one node is found in given level and another is not found, then given nodes are not cousins.
Steps to solve this problem:
1. Check if root is null than return false.
2. Declare two pointers parA=null and parB=null.
3. Declare a queue pair q of pointer to a node both.
4. Declare a pointer to a new node tmp with value -1.
5. Declare a pair ele of pointer to a node both.
6. Push (root,tmp) in q and declare a variable levsize.
7. While q is not empty:
*Update levsize =q.size
*While levsize is not zero:
*Update ele=q.front and pop the element after that.
*Check if ele.first->data is equal to a->data than parA=ele.second
*Check if ele.first->data is equal to b->data than parB=ele.second
*Check if ele.first->left is not null than push (ele.first->left,ele.first) in q.
*Check if ele.first->right is not null than push (ele.first->right,ele.first) in q.
*Decrement levsize.
*Check parA logical AND parB is true than break.
*Check if parA logical AND parB is true than return parA not equal to parB.
*Check if (parA && !parB)||(parB && !parA) is true than return false.
8. Return false.
Below is the implementation of above approach:
C++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
struct Node *left, *right;
};
struct Node* newNode( int item)
{
struct Node* temp = ( struct Node*) malloc ( sizeof ( struct Node));
temp->data = item;
temp->left = temp->right = NULL;
return temp;
}
bool isCousin(Node* root, Node* a, Node* b)
{
if (root == NULL)
return false ;
Node* parA = NULL;
Node* parB = NULL;
queue<pair<Node*, Node*> > q;
Node* tmp = newNode(-1);
pair<Node*, Node*> ele;
q.push(make_pair(root, tmp));
int levSize;
while (!q.empty()) {
levSize = q.size();
while (levSize) {
ele = q.front();
q.pop();
if (ele.first->data == a->data) {
parA = ele.second;
}
if (ele.first->data == b->data) {
parB = ele.second;
}
if (ele.first->left) {
q.push(make_pair(ele.first->left, ele.first));
}
if (ele.first->right) {
q.push(make_pair(ele.first->right, ele.first));
}
levSize--;
if (parA && parB)
break ;
}
if (parA && parB) {
return parA != parB;
}
if ((parA && !parB) || (parB && !parA)) {
return false ;
}
}
return false ;
}
int main()
{
struct Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->left->right->right = newNode(15);
root->right->left = newNode(6);
root->right->right = newNode(7);
root->right->left->right = newNode(8);
struct Node *Node1, *Node2;
Node1 = root->left->left;
Node2 = root->right->right;
isCousin(root, Node1, Node2) ? puts ( "Yes" ) : puts ( "No" );
return 0;
}
|
Java
import java.util.*;
import javafx.util.Pair;
class Node
{
int data;
Node left, right;
Node( int item)
{
data = item;
left = right = null ;
}
}
class BinaryTree
{
Node root;
boolean isCousin(Node node, Node a, Node b)
{
if (node == null )
return false ;
Node parA = null ;
Node parB = null ;
Queue<Pair <Node,Node>> q = new LinkedList<> ();
Node tmp = new Node(- 1 );
Pair<Node, Node> ele;
q.add( new Pair <Node,Node> (node, tmp));
int levelSize;
while (!q.isEmpty())
{
levelSize = q.size();
while (levelSize != 0 )
{
ele = q.peek();
q.remove();
if (ele.getKey().data == a.data)
parA = ele.getValue();
if (ele.getKey().data == b.data)
parB = ele.getValue();
if (ele.getKey().left != null )
q.add( new Pair<Node, Node>(ele.getKey().left, ele.getKey()));
if (ele.getKey().right != null )
q.add( new Pair<Node, Node>(ele.getKey().right, ele.getKey()));
levelSize--;
if (parA != null && parB != null )
break ;
}
if (parA != null && parB != null )
return parA != parB;
if ((parA!= null && parB== null ) || (parB!= null && parA== null ))
return false ;
}
return false ;
}
public static void main(String args[])
{
BinaryTree tree = new BinaryTree();
tree.root = new Node( 1 );
tree.root.left = new Node( 2 );
tree.root.right = new Node( 3 );
tree.root.left.left = new Node( 4 );
tree.root.left.right = new Node( 5 );
tree.root.left.right.right = new Node( 15 );
tree.root.right.left = new Node( 6 );
tree.root.right.right = new Node( 7 );
tree.root.right.left.right = new Node( 8 );
Node Node1, Node2;
Node1 = tree.root.left.right.right;
Node2 = tree.root.right.left.right;
if (tree.isCousin(tree.root, Node1, Node2))
System.out.println( "Yes" );
else
System.out.println( "No" );
}
}
|
Python3
class Node:
def __init__( self , item):
self .data = item
self .left = None
self .right = None
def isCousin(root, a, b):
if root = = None :
return False
parA = None
parB = None
q = []
tmp = Node( - 1 )
q.append((root, tmp))
while len (q) > 0 :
levSize = len (q)
while levSize:
ele = q.pop( 0 )
if ele[ 0 ].data = = a.data:
parA = ele[ 1 ]
if ele[ 0 ].data = = b.data:
parB = ele[ 1 ]
if ele[ 0 ].left:
q.append((ele[ 0 ].left, ele[ 0 ]))
if ele[ 0 ].right:
q.append((ele[ 0 ].right, ele[ 0 ]))
levSize - = 1
if parA and parB:
break
if parA and parB:
return parA ! = parB
if (parA and not parB) or (parB and not parA):
return False
return False
if __name__ = = '__main__' :
root = Node( 1 )
root.left = Node( 2 )
root.right = Node( 3 )
root.left.left = Node( 4 )
root.left.right = Node( 5 )
root.left.right.right = Node( 15 )
root.right.left = Node( 6 )
root.right.right = Node( 7 )
root.right.left.right = Node( 8 )
Node1 = root.left.left
Node2 = root.right.right
if isCousin(root, Node1, Node2):
print ( 'Yes' )
else :
print ( 'No' )
|
C#
using System;
using System.Collections.Generic;
public class Node
{
public int data;
public Node left, right;
public Node( int item)
{
data = item;
left = right = null ;
}
}
public class Pair
{
public Node first, second;
public Pair(Node first, Node second)
{
this .first = first;
this .second = second;
}
}
class BinaryTree
{
Node root;
Boolean isCousin(Node node, Node a, Node b)
{
if (node == null )
return false ;
Node parA = null ;
Node parB = null ;
Queue<Pair > q = new Queue<Pair > ();
Node tmp = new Node(-1);
Pair ele;
q.Enqueue( new Pair (node, tmp));
int levelSize;
while (q.Count>0)
{
levelSize = q.Count;
while (levelSize != 0)
{
ele = q.Peek();
q.Dequeue();
if (ele.first.data == a.data)
parA = ele.second;
if (ele.first.data == b.data)
parB = ele.second;
if (ele.first.left != null )
q.Enqueue( new Pair(ele.first.left, ele.first));
if (ele.first.right != null )
q.Enqueue( new Pair(ele.first.right, ele.first));
levelSize--;
if (parA != null && parB != null )
break ;
}
if (parA != null && parB != null )
return parA != parB;
if ((parA != null && parB == null ) || (parB != null && parA == null ))
return false ;
}
return false ;
}
public static void Main(String []args)
{
BinaryTree tree = new BinaryTree();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);
tree.root.left.right.right = new Node(15);
tree.root.right.left = new Node(6);
tree.root.right.right = new Node(7);
tree.root.right.left.right = new Node(8);
Node Node1, Node2;
Node1 = tree.root.left.right.right;
Node2 = tree.root.right.left.right;
if (tree.isCousin(tree.root, Node1, Node2))
Console.WriteLine( "Yes" );
else
Console.WriteLine( "No" );
}
}
|
Javascript
<script>
class Node
{
constructor(item)
{
this .data = item;
this .left = null ;
this .right = null ;
}
}
class Pair
{
constructor(first, second)
{
this .first = first;
this .second = second;
}
}
var root = null ;
function isCousin(node, a, b)
{
if (node == null )
return false ;
var parA = null ;
var parB = null ;
var q = [];
var tmp = new Node(-1);
var ele;
q.push( new Pair (node, tmp));
var levelSize;
while (q.length>0)
{
levelSize = q.length;
while (levelSize != 0)
{
ele = q[0];
q.shift();
if (ele.first.data == a.data)
parA = ele.second;
if (ele.first.data == b.data)
parB = ele.second;
if (ele.first.left != null )
q.push( new Pair(ele.first.left, ele.first));
if (ele.first.right != null )
q.push( new Pair(ele.first.right, ele.first));
levelSize--;
if (parA != null && parB != null )
break ;
}
if (parA != null && parB != null )
return parA != parB;
if ((parA != null && parB == null ) || (parB != null
&& parA == null ))
return false ;
}
return false ;
}
root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.left.right.right = new Node(15);
root.right.left = new Node(6);
root.right.right = new Node(7);
root.right.left.right = new Node(8);
var Node1, Node2;
Node1 = root.left.right.right;
Node2 = root.right.left.right;
if (isCousin(root, Node1, Node2))
document.write( "Yes" );
else
document.write( "No" );
</script>
|
Complexity Analysis:
- Time Complexity: O(n)
- Auxiliary Space: O(n)
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!