# Find the cousins of a given element in an N-ary tree

• Last Updated : 31 Jan, 2022

Given an N-array tree root and an integer K, the task is to print all the cousins of node K.

Note: Two nodes are considered to be cousins if they have the same depth (are on the same level) and have different parents.

Examples:

Consider the below tree:

Input: K = 39
Output: 88 98 61 74 17 72 19

Input: K = 17
Output: 88 98 61 74 39

Input: K = 90
Output: NA

Approach: The idea is to do a level order traversal. During the traversal, if we find a node whose child is equal to the given element, then we will not push the children of this node. We will push the children of the other nodes and the inner loop will end when all the elements of that level are traversed. Follow the steps below to solve the problem:

• If root equals null, then return.
• Initialize the queue q[] and push root into the queue q[].
• Initialize the boolean variable found as false.
• Initialize the variables qsize as 0 and node temp.
• Iterate over the while loop till q[] is not empty and node is not found and perform the following tasks:
• Set size qsize as the size of the queue q[].
• Iterate over the while loop till qsize is greater than 0 and perform the following tasks:
• Set tempp as the front of the queue q[].
• De queue from the queue q[].
• If found equals true, then push all it’s children into the queue q[].
• Iterate over the range [0, temp->child.size()) using the variable i and perform the following tasks:
• If the child is not null and it’s key equals value, then set the value of found as true.
• If found is false, then push all it’s children into the queue q[].
• Decrease the value of qsize by 1.
• If found is false, then print “Not Possible.”
• Else, Initialize the variables qsize as the size of the queue q[].
• If qsize equals 0 then print “No Cousins”.
• Else, print all the elements of the queue q[].

Below is the implementation of the above approach

## C++

 `// C++ program for the above approach` `#include ` `using` `namespace` `std;`   `// Structure of a node of N-ary tree` `struct` `Node {` `    ``int` `key;` `    ``vector child;` `};`   `// New node creation` `Node* newNode(``int` `key)` `{` `    ``Node* temp = ``new` `Node;` `    ``temp->key = key;` `    ``return` `temp;` `}`   `// Function to find the cousins of a` `// given node in an N-array tree` `void` `printCousins(Node* root, ``int` `value)` `{`   `    ``// Base case` `    ``if` `(root == NULL)` `        ``return``;`   `    ``queue q;` `    ``q.push(root);`   `    ``// If we find the node` `    ``// with value as the key` `    ``bool` `found = ``false``;`   `    ``int` `qsize = 0;` `    ``Node* tempp;`   `    ``while` `(!q.empty() && !found) {` `        ``qsize = q.size();`   `        ``while` `(qsize) {`   `            ``// Storing the current node` `            ``tempp = q.front();` `            ``q.pop();`   `            ``// If we have already found` `            ``// the value as child of a node,` `            ``// we need to insert children of other` `            ``// node of same level in the queue` `            ``if` `(found == ``true``) {` `                ``for` `(``int` `i = 0; i < tempp->child.size();` `                     ``i++) {` `                    ``if` `(tempp->child[i] != NULL)` `                        ``q.push(tempp->child[i]);` `                ``}` `            ``}`   `            ``// If value is child of tempp node` `            ``for` `(``int` `i = 0; i < tempp->child.size(); i++)` `                ``if` `(tempp->child[i] != NULL` `                    ``&& tempp->child[i]->key == value)` `                    ``found = ``true``;`   `            ``// If value is not the child of tempp node` `            ``// then insert all the children` `            ``// of the tempp node` `            ``if` `(found == ``false``) {` `                ``for` `(``int` `i = 0; i < tempp->child.size();` `                     ``i++) {` `                    ``if` `(tempp->child[i] != NULL)` `                        ``q.push(tempp->child[i]);` `                ``}` `            ``}`   `            ``qsize--;` `        ``}` `    ``}`   `    ``if` `(found) {`   `        ``// Queue will contain the cousins` `        ``qsize = q.size();`   `        ``if` `(qsize == 0)` `            ``cout << ``"NA"``;` `        ``for` `(``int` `i = 0; i < qsize; i++) {` `            ``tempp = q.front();` `            ``q.pop();` `            ``cout << tempp->key << ``" "``;` `        ``}` `    ``}` `    ``else` `{`   `        ``// When value  is not in the tree` `        ``cout << ``"Not Possible"``;` `    ``}` `    ``cout << ``"\n"``;` `    ``return``;` `}`   `// Driver Code` `int` `main()` `{`   `    ``Node* root = newNode(10);` `    ``(root->child).push_back(newNode(77));` `    ``(root->child).push_back(newNode(90));` `    ``(root->child).push_back(newNode(35));` `    ``(root->child).push_back(newNode(19));` `    ``(root->child[0]->child).push_back(newNode(88));` `    ``(root->child[0]->child).push_back(newNode(98));` `    ``(root->child[0]->child[1]->child)` `        ``.push_back(newNode(76));` `    ``(root->child[0]->child[1]->child)` `        ``.push_back(newNode(20));` `    ``(root->child[1]->child).push_back(newNode(61));` `    ``(root->child[1]->child).push_back(newNode(74));` `    ``(root->child[2]->child).push_back(newNode(39));` `    ``(root->child[3]->child).push_back(newNode(17));` `    ``(root->child[3]->child).push_back(newNode(72));` `    ``(root->child[3]->child).push_back(newNode(19));`   `    ``// Find the cousins of value` `    ``int` `value = 39;` `    ``printCousins(root, value);`   `    ``return` `0;` `}`

## Java

 `// Java program for the above approach` `import` `java.util.*;`   `class` `GFG{`   `  ``// Structure of a node of N-ary tree` `  ``static` `class` `Node {` `    ``int` `key;` `    ``Vector child = ``new` `Vector();` `  ``};`   `  ``// New node creation` `  ``static` `Node newNode(``int` `key)` `  ``{` `    ``Node temp = ``new` `Node();` `    ``temp.key = key;` `    ``return` `temp;` `  ``}`   `  ``// Function to find the cousins of a` `  ``// given node in an N-array tree` `  ``static` `void` `printCousins(Node root, ``int` `value)` `  ``{`   `    ``// Base case` `    ``if` `(root == ``null``)` `      ``return``;`   `    ``Queue q = ``new` `LinkedList();` `    ``q.add(root);`   `    ``// If we find the node` `    ``// with value as the key` `    ``boolean` `found = ``false``;`   `    ``int` `qsize = ``0``;` `    ``Node tempp;`   `    ``while` `(!q.isEmpty() && !found) {` `      ``qsize = q.size();`   `      ``while` `(qsize > ``0``) {`   `        ``// Storing the current node` `        ``tempp = q.peek();` `        ``q.remove();`   `        ``// If we have already found` `        ``// the value as child of a node,` `        ``// we need to insert children of other` `        ``// node of same level in the queue` `        ``if` `(found == ``true``) {` `          ``for` `(``int` `i = ``0``; i < tempp.child.size();` `               ``i++) {` `            ``if` `(tempp.child.get(i) != ``null``)` `              ``q.add(tempp.child.get(i));` `          ``}` `        ``}`   `        ``// If value is child of tempp node` `        ``for` `(``int` `i = ``0``; i < tempp.child.size(); i++)` `          ``if` `(tempp.child.get(i) != ``null` `              ``&& tempp.child.get(i).key == value)` `            ``found = ``true``;`   `        ``// If value is not the child of tempp node` `        ``// then insert all the children` `        ``// of the tempp node` `        ``if` `(found == ``false``) {` `          ``for` `(``int` `i = ``0``; i < tempp.child.size();` `               ``i++) {` `            ``if` `(tempp.child.get(i) != ``null``)` `              ``q.add(tempp.child.get(i));` `          ``}` `        ``}`   `        ``qsize--;` `      ``}` `    ``}`   `    ``if` `(found) {`   `      ``// Queue will contain the cousins` `      ``qsize = q.size();`   `      ``if` `(qsize == ``0``)` `        ``System.out.print(``"NA"``);` `      ``for` `(``int` `i = ``0``; i < qsize; i++) {` `        ``tempp = q.peek();` `        ``q.remove();` `        ``System.out.print(tempp.key+ ``" "``);` `      ``}` `    ``}` `    ``else` `{`   `      ``// When value  is not in the tree` `      ``System.out.print(``"Not Possible"``);` `    ``}` `    ``System.out.print(``"\n"``);` `    ``return``;` `  ``}`   `  ``// Driver Code` `  ``public` `static` `void` `main(String[] args)` `  ``{`   `    ``Node root = newNode(``10``);` `    ``(root.child).add(newNode(``77``));` `    ``(root.child).add(newNode(``90``));` `    ``(root.child).add(newNode(``35``));` `    ``(root.child).add(newNode(``19``));` `    ``(root.child.get(``0``).child).add(newNode(``88``));` `    ``(root.child.get(``0``).child).add(newNode(``98``));` `    ``(root.child.get(``0``).child.get(``1``).child)` `    ``.add(newNode(``76``));` `    ``(root.child.get(``0``).child.get(``1``).child)` `    ``.add(newNode(``20``));` `    ``(root.child.get(``1``).child).add(newNode(``61``));` `    ``(root.child.get(``1``).child).add(newNode(``74``));` `    ``(root.child.get(``2``).child).add(newNode(``39``));` `    ``(root.child.get(``3``).child).add(newNode(``17``));` `    ``(root.child.get(``3``).child).add(newNode(``72``));` `    ``(root.child.get(``3``).child).add(newNode(``19``));`   `    ``// Find the cousins of value` `    ``int` `value = ``39``;` `    ``printCousins(root, value);`   `  ``}` `}`   `// This code is contributed by shikhasingrajput`

## Python3

 `# Python code for the above approach `   `# Structure of a node of N-ary tree` `class` `Node:` `    ``def` `__init__ (``self``, k):` `        ``self``.key ``=` `k;` `        ``self``.child ``=` `[];`   `# node creation`   `# Function to find the cousins of a` `# given node in an N-array tree` `def` `printCousins(root, value):`   `    ``# Base case` `    ``if` `(root ``=``=` `None``):` `        ``return``;`   `    ``q ``=` `[];` `    ``q.append(root);`   `    ``# If we find the node` `    ``# with value as the key` `    ``found ``=` `False``;`   `    ``qsize ``=` `0``;` `    ``tempp ``=` `None`   `    ``while` `(``len``(q) !``=` `0` `and` `found !``=` `1``):` `        ``qsize ``=` `len``(q);`   `        ``while` `(qsize !``=` `0``):`   `            ``# Storing the current node` `            ``tempp ``=` `q[``0``];` `            ``q.pop(``0``);`   `            ``# If we have already found` `            ``# the value as child of a node,` `            ``# we need to insert children of other` `            ``# node of same level in the queue` `            ``if` `(found ``=``=` `True``):` `                ``for` `i ``in` `range``(``len``(tempp.child)):` `                    ``if` `(tempp.child[i] !``=` `None``):` `                        ``q.append(tempp.child[i]);`   `            ``# If value is child of tempp node` `            ``for` `i ``in` `range``(``len``(tempp.child)):` `                ``if` `(tempp.child[i] !``=` `None` `and` `tempp.child[i].key ``=``=` `value):` `                    ``found ``=` `True``;`   `            ``# If value is not the child of tempp node` `            ``# then insert all the children` `            ``# of the tempp node` `            ``if` `(found ``=``=` `False``):` `                ``for` `i ``in` `range``(``len``(tempp.child)):` `                    ``if` `(tempp.child[i] !``=` `None``):` `                        ``q.append(tempp.child[i]);`   `            ``qsize ``-``=` `1`   `    ``if` `(found):`   `        ``# Queue will contain the cousins` `        ``qsize ``=` `len``(q);`   `        ``if` `(qsize ``=``=` `0``):` `            ``print``(``"NA"``);` `        ``for` `i ``in` `range``(qsize):` `            ``tempp ``=` `q[``0``];` `            ``q.pop(``0``);` `            ``print``(tempp.key, end``=` `" "``);` `    ``else``:`   `        ``# When value  is not in the tree` `        ``print``(``"Not Possible"``);` `    ``print``('')` `    ``return``;`   `# Driver Code` `root ``=` `Node(``10``);` `root.child.append(Node(``77``));` `root.child.append(Node(``90``));` `root.child.append(Node(``35``));` `root.child.append(Node(``19``));` `root.child[``0``].child.append(Node(``88``));` `root.child[``0``].child.append(Node(``98``));` `root.child[``0``].child[``1``].child.append(Node(``76``));` `root.child[``0``].child[``1``].child.append(Node(``20``));` `root.child[``1``].child.append(Node(``61``));` `root.child[``1``].child.append(Node(``74``));` `root.child[``2``].child.append(Node(``39``));` `root.child[``3``].child.append(Node(``17``));` `root.child[``3``].child.append(Node(``72``));` `root.child[``3``].child.append(Node(``19``));`   `# Find the cousins of value` `value ``=` `39``;` `printCousins(root, value);`   `# This code is contributed by gfgking`

## C#

 `// C# program for the above approach` `using` `System;` `using` `System.Collections.Generic;`   `public` `class` `GFG{`   `  ``// Structure of a node of N-ary tree` `  ``class` `Node {` `    ``public` `int` `key;` `    ``public` `List child = ``new` `List();` `  ``};`   `  ``// New node creation` `  ``static` `Node newNode(``int` `key)` `  ``{` `    ``Node temp = ``new` `Node();` `    ``temp.key = key;` `    ``return` `temp;` `  ``}`   `  ``// Function to find the cousins of a` `  ``// given node in an N-array tree` `  ``static` `void` `printCousins(Node root, ``int` `value)` `  ``{`   `    ``// Base case` `    ``if` `(root == ``null``)` `      ``return``;`   `    ``Queue q = ``new` `Queue();` `    ``q.Enqueue(root);`   `    ``// If we find the node` `    ``// with value as the key` `    ``bool` `found = ``false``;`   `    ``int` `qsize = 0;` `    ``Node tempp;`   `    ``while` `(q.Count!=0 && !found) {` `      ``qsize = q.Count;`   `      ``while` `(qsize > 0) {`   `        ``// Storing the current node` `        ``tempp = q.Peek();` `        ``q.Dequeue();`   `        ``// If we have already found` `        ``// the value as child of a node,` `        ``// we need to insert children of other` `        ``// node of same level in the queue` `        ``if` `(found == ``true``) {` `          ``for` `(``int` `i = 0; i < tempp.child.Count;` `               ``i++) {` `            ``if` `(tempp.child[i] != ``null``)` `              ``q.Enqueue(tempp.child[i]);` `          ``}` `        ``}`   `        ``// If value is child of tempp node` `        ``for` `(``int` `i = 0; i < tempp.child.Count; i++)` `          ``if` `(tempp.child[i] != ``null` `              ``&& tempp.child[i].key == value)` `            ``found = ``true``;`   `        ``// If value is not the child of tempp node` `        ``// then insert all the children` `        ``// of the tempp node` `        ``if` `(found == ``false``) {` `          ``for` `(``int` `i = 0; i < tempp.child.Count;` `               ``i++) {` `            ``if` `(tempp.child[i] != ``null``)` `              ``q.Enqueue(tempp.child[i]);` `          ``}` `        ``}`   `        ``qsize--;` `      ``}` `    ``}`   `    ``if` `(found) {`   `      ``// Queue will contain the cousins` `      ``qsize = q.Count;`   `      ``if` `(qsize == 0)` `        ``Console.Write(``"NA"``);` `      ``for` `(``int` `i = 0; i < qsize; i++) {` `        ``tempp = q.Peek();` `        ``q.Dequeue();` `        ``Console.Write(tempp.key+ ``" "``);` `      ``}` `    ``}` `    ``else` `{`   `      ``// When value  is not in the tree` `      ``Console.Write(``"Not Possible"``);` `    ``}` `    ``Console.Write(``"\n"``);` `    ``return``;` `  ``}`   `  ``// Driver Code` `  ``public` `static` `void` `Main(String[] args)` `  ``{`   `    ``Node root = newNode(10);` `    ``(root.child).Add(newNode(77));` `    ``(root.child).Add(newNode(90));` `    ``(root.child).Add(newNode(35));` `    ``(root.child).Add(newNode(19));` `    ``(root.child[0].child).Add(newNode(88));` `    ``(root.child[0].child).Add(newNode(98));` `    ``(root.child[0].child[1].child)` `    ``.Add(newNode(76));` `    ``(root.child[0].child[1].child)` `    ``.Add(newNode(20));` `    ``(root.child[1].child).Add(newNode(61));` `    ``(root.child[1].child).Add(newNode(74));` `    ``(root.child[2].child).Add(newNode(39));` `    ``(root.child[3].child).Add(newNode(17));` `    ``(root.child[3].child).Add(newNode(72));` `    ``(root.child[3].child).Add(newNode(19));`   `    ``// Find the cousins of value` `    ``int` `value = 39;` `    ``printCousins(root, value);`   `  ``}` `}`       `// This code is contributed by 29AjayKumar`

## Javascript

 ``

Output

`Cousins for the element 39: 88 98 61 74 17 72 19 `

Time Complexity: O(N)
Auxiliary Space: O(N)

My Personal Notes arrow_drop_up
Related Articles