Open In App

Print cousins of a given node in Binary Tree

Improve
Improve
Like Article
Like
Save
Share
Report

Given a binary tree and a node, print all cousins of given node. Note that siblings should not be printed.
Example: 
 

Input : root of below tree 
             1
           /   \
          2     3
        /   \  /  \
       4    5  6   7
       and pointer to a node say 5.

Output : 6, 7

The idea to first find level of given node using the approach discussed here. Once we have found level, we can print all nodes at a given level using the approach discussed here. The only thing to take care of is, sibling should not be printed. To handle this, we change the printing function to first check for sibling and print node only if it is not sibling.

Below is the implementation of above idea. 

C++




// C++ program to print cousins of a node
#include <bits/stdc++.h>
using namespace std;
 
// A Binary Tree Node
struct Node
{
    int data;
    Node *left, *right;
};
 
// A utility function to create a new
// Binary Tree Node
Node *newNode(int item)
{
    Node *temp = new Node;
    temp->data = item;
    temp->left = temp->right = NULL;
    return temp;
}
 
/* It returns level of the node if it is
present in tree, otherwise returns 0.*/
int getLevel(Node *root, Node *node, int level)
{
     
    // base cases
    if (root == NULL)
        return 0;
    if (root == node)
        return level;
 
    // If node is present in left subtree
    int downlevel = getLevel(root->left,
                             node, level + 1);
    if (downlevel != 0)
        return downlevel;
 
    // If node is not present in left subtree
    return getLevel(root->right, node, level + 1);
}
 
/* Print nodes at a given level such that
sibling of node is not printed if it exists */
void printGivenLevel(Node* root, Node *node, int level)
{
    // Base cases
    if (root == NULL || level < 2)
        return;
 
    // If current node is parent of a node
    // with given level
    if (level == 2)
    {
        if (root->left == node || root->right == node)
            return;
        if (root->left)
            cout << root->left->data << " ";
        if (root->right)
            cout << root->right->data;
    }
 
    // Recur for left and right subtrees
    else if (level > 2)
    {
        printGivenLevel(root->left, node, level - 1);
        printGivenLevel(root->right, node, level - 1);
    }
}
 
// This function prints cousins of a given node
void printCousins(Node *root, Node *node)
{
    // Get level of given node
    int level = getLevel(root, node, 1);
 
    // Print nodes of given level.
    printGivenLevel(root, node, level);
}
 
// Driver Code
int main()
{
    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);
 
    printCousins(root, root->left->right);
 
    return 0;
}
 
// This code is contributed
// by Akanksha Rai


C




// C program to print cousins of a node
#include <stdio.h>
#include <stdlib.h>
 
// A Binary Tree Node
struct Node
{
    int data;
    Node *left, *right;
};
 
// A utility function to create a new Binary
// Tree Node
Node *newNode(int item)
{
    Node *temp =  new Node;
    temp->data = item;
    temp->left = temp->right = NULL;
    return temp;
}
 
/* It returns level of the node if it is present
   in tree, otherwise returns 0.*/
int getLevel(Node *root, Node *node, int level)
{
    // base cases
    if (root == NULL)
        return 0;
    if (root == node)
        return level;
 
    // If node is present in left subtree
    int downlevel = getLevel(root->left, node, level+1);
    if (downlevel != 0)
        return downlevel;
 
    // If node is not present in left subtree
    return getLevel(root->right, node, level+1);
}
 
/* Print nodes at a given level such that sibling of
   node is not printed if it exists  */
void printGivenLevel(Node* root, Node *node, int level)
{
    // Base cases
    if (root == NULL || level < 2)
        return;
 
    // If current node is parent of a node with
    // given level
    if (level == 2)
    {
        if (root->left == node || root->right == node)
            return;
        if (root->left)
           printf("%d ", root->left->data);
        if (root->right)
           printf("%d ", root->right->data);
    }
 
    // Recur for left and right subtrees
    else if (level > 2)
    {
        printGivenLevel(root->left, node, level-1);
        printGivenLevel(root->right, node, level-1);
    }
}
 
// This function prints cousins of a given node
void printCousins(Node *root, Node *node)
{
    // Get level of given node
    int level = getLevel(root, node, 1);
 
    // Print nodes of given level.
    printGivenLevel(root, node, level);
}
 
// Driver Program to test above functions
int main()
{
    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);
 
    printCousins(root, root->left->right);
 
    return 0;
}


Java




// Java program to print cousins of a node
public class GfG {
 
// A Binary Tree Node
static class Node
{
    int data;
    Node left, right;
}
 
// A utility function to create a new Binary
// Tree Node
static Node newNode(int item)
{
    Node temp = new Node();
    temp.data = item;
    temp.left = null;
    temp.right = null;
    return temp;
}
 
/* It returns level of the node if it is present
in tree, otherwise returns 0.*/
static int getLevel(Node root, Node node, int level)
{
    // base cases
    if (root == null)
        return 0;
    if (root == node)
        return level;
 
    // If node is present in left subtree
    int downlevel = getLevel(root.left, node, level+1);
    if (downlevel != 0)
        return downlevel;
 
    // If node is not present in left subtree
    return getLevel(root.right, node, level+1);
}
 
/* Print nodes at a given level such that sibling of
node is not printed if it exists */
static void printGivenLevel(Node root, Node node, int level)
{
    // Base cases
    if (root == null || level < 2)
        return;
 
    // If current node is parent of a node with
    // given level
    if (level == 2)
    {
        if (root.left == node || root.right == node)
            return;
        if (root.left != null)
        System.out.print(root.left.data + " ");
        if (root.right != null)
        System.out.print(root.right.data + " ");
    }
 
    // Recur for left and right subtrees
    else if (level > 2)
    {
        printGivenLevel(root.left, node, level-1);
        printGivenLevel(root.right, node, level-1);
    }
}
 
// This function prints cousins of a given node
static void printCousins(Node root, Node node)
{
    // Get level of given node
    int level = getLevel(root, node, 1);
 
    // Print nodes of given level.
    printGivenLevel(root, node, level);
}
 
// Driver Program to test above functions
public static void main(String[] args)
{
    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);
 
    printCousins(root, root.left.right);
}
}


Python3




# Python3 program to print cousins of a node
 
# A utility function to create a new
# Binary Tree Node
class newNode:
    def __init__(self, item):
        self.data = item
        self.left = self.right = None
 
# It returns level of the node if it is
# present in tree, otherwise returns 0.
def getLevel(root, node, level):
     
    # base cases
    if (root == None):
        return 0
    if (root == node):
        return level
 
    # If node is present in left subtree
    downlevel = getLevel(root.left, node,
                               level + 1)
    if (downlevel != 0):
        return downlevel
 
    # If node is not present in left subtree
    return getLevel(root.right, node, level + 1)
 
# Print nodes at a given level such that
# sibling of node is not printed if
# it exists
def printGivenLevel(root, node, level):
     
    # Base cases
    if (root == None or level < 2):
        return
 
    # If current node is parent of a
    # node with given level
    if (level == 2):
        if (root.left == node or
            root.right == node):
            return
        if (root.left):
            print(root.left.data, end = " ")
        if (root.right):
            print(root.right.data, end = " ")
 
    # Recur for left and right subtrees
    elif (level > 2):
        printGivenLevel(root.left, node, level - 1)
        printGivenLevel(root.right, node, level - 1)
 
# This function prints cousins of a given node
def printCousins(root, node):
     
    # Get level of given node
    level = getLevel(root, node, 1)
 
    # Print nodes of given level.
    printGivenLevel(root, node, level)
 
# Driver Code
if __name__ == '__main__':
    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)
 
    printCousins(root, root.left.right)
     
# This code is contributed by PranchalK


C#




// C# program to print cousins of a node
using System;
 
public class GfG
{
 
// A Binary Tree Node
class Node
{
    public int data;
    public Node left, right;
}
 
// A utility function to create 
// a new Binary Tree Node
static Node newNode(int item)
{
    Node temp = new Node();
    temp.data = item;
    temp.left = null;
    temp.right = null;
    return temp;
}
 
/* It returns level of the node
if it is present in tree,
 otherwise returns 0.*/
static int getLevel(Node root,
            Node node, int level)
{
    // base cases
    if (root == null)
        return 0;
    if (root == node)
        return level;
 
    // If node is present in left subtree
    int downlevel = getLevel(root.left, node, level + 1);
    if (downlevel != 0)
        return downlevel;
 
    // If node is not present in left subtree
    return getLevel(root.right, node, level + 1);
}
 
/* Print nodes at a given level
such that sibling of node is
 not printed if it exists */
static void printGivenLevel(Node root,
                    Node node, int level)
{
    // Base cases
    if (root == null || level < 2)
        return;
 
    // If current node is parent of a node with
    // given level
    if (level == 2)
    {
        if (root.left == node || root.right == node)
            return;
        if (root.left != null)
            Console.Write(root.left.data + " ");
        if (root.right != null)
            Console.Write(root.right.data + " ");
    }
 
    // Recur for left and right subtrees
    else if (level > 2)
    {
        printGivenLevel(root.left, node, level - 1);
        printGivenLevel(root.right, node, level - 1);
    }
}
 
// This function prints cousins of a given node
static void printCousins(Node root, Node node)
{
    // Get level of given node
    int level = getLevel(root, node, 1);
 
    // Print nodes of given level.
    printGivenLevel(root, node, level);
}
 
// Driver code
public static void Main(String[] args)
{
    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);
 
    printCousins(root, root.left.right);
}
}
 
// This code is contributed Rajput-Ji


Javascript




<script>
  
// JavaScript program to print cousins of a node
 
// A Binary Tree Node
class Node
{
  constructor()
  {
    this.data=0;
    this.left= null;
    this.right = null;
  }
}
 
// A utility function to create 
// a new Binary Tree Node
function newNode(item)
{
    var temp = new Node();
    temp.data = item;
    temp.left = null;
    temp.right = null;
    return temp;
}
 
/* It returns level of the node
if it is present in tree,
 otherwise returns 0.*/
function getLevel(root, node, level)
{
    // base cases
    if (root == null)
        return 0;
    if (root == node)
        return level;
 
    // If node is present in left subtree
    var downlevel = getLevel(root.left, node, level + 1);
    if (downlevel != 0)
        return downlevel;
 
    // If node is not present in left subtree
    return getLevel(root.right, node, level + 1);
}
 
/* Print nodes at a given level
such that sibling of node is
 not printed if it exists */
function printGivenLevel(root, node, level)
{
    // Base cases
    if (root == null || level < 2)
        return;
 
    // If current node is parent of a node with
    // given level
    if (level == 2)
    {
        if (root.left == node || root.right == node)
            return;
        if (root.left != null)
            document.write(root.left.data + " ");
        if (root.right != null)
            document.write(root.right.data + " ");
    }
 
    // Recur for left and right subtrees
    else if (level > 2)
    {
        printGivenLevel(root.left, node, level - 1);
        printGivenLevel(root.right, node, level - 1);
    }
}
 
// This function prints cousins of a given node
function printCousins(root, node)
{
    // Get level of given node
    var level = getLevel(root, node, 1);
 
    // Print nodes of given level.
    printGivenLevel(root, node, level);
}
 
// Driver code
var 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);
printCousins(root, root.left.right);
 
</script>


Output

6 7

Time Complexity : O(n)
Auxiliary Space: O(n) due to recursion.

Another Approach(Iterative Approach):
An efficient and easy to implement approach by level order traversal using queue.
Follow the below steps to solve this problem:
1) First perform level order traversal using queue.
2) Check for each node that its left or right child is match with target(given) node then don’t insert its childrens and mark found variable to true but insert other nodes of just upper nodes in queue.
3) After insert all the nodes print them and return.

Below is the implementation of above approach:

C++




// C++ program to print cousins of a node
#include <bits/stdc++.h>
using namespace std;
 
// A Binary Tree Node
struct Node{
    int data;
    Node *left, *right;
};
 
// return a new tree node
Node *newNode(int data){
    Node *temp = new Node;
    temp->data = data;
    temp->left = temp->right = NULL;
    return temp;
}
 
// function prints the cousins of a given node
void printCousins(Node *root, Node *node){
    // base condition
    if(root == NULL) return;
    // initializing bool function to track target node
    // is found or not
    bool found = false;
    // initializing queue to perform level order traversal
    queue<Node*> q;
    q.push(root);
    while(!q.empty()){
        int n = q.size();
        for(int i = 0; i<n; i++){
            Node* temp = q.front();
            q.pop();
            if(temp->left == node || temp->right == node){
                found = true;
            }else{
                if(temp->left) q.push(temp->left);
                if(temp->right) q.push(temp->right);
            }
        }
        if(found){
            while(!q.empty()){
                cout<<q.front()->data<<" ";
                q.pop();
            }
            cout<<endl;
            return;
        }
    }
}
 
// Driver Code to test above function
int main()
{
    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);
 
    printCousins(root, root->left->right);
 
    return 0;
}
// THIS CODE IS CONTRIBUTED BY YASH AGARWAL(YASHAGARWAL2852002)


Java




/*package whatever //do not write package name here */
 
import java.io.*;
import java.util.*;
// java program to print cousins of a node
 
// A Binary Tree Node
class Node{
  int data;
  Node left;
  Node right;
 
  Node(int d){
    data = d;
    left = null;
    right = null;
  }
}
 
 
public class Main {
 
  // function prints the cousins of a given node
  public static void printCousins(Node root, Node node){
    // base condition
    if(root == null) return;
    // initializing bool function to track target node
    // is found or not
    boolean found = false;
    // initializing queue to perform level order traversal
    Queue<Node> q = new LinkedList<>();
    q.add(root);
    while(q.size() > 0){
      int n = q.size();
      for(int i = 0; i<n; i++){
        Node temp = q.remove();
        if(temp.left == node || temp.right == node){
          found = true;
        }else{
          if(temp.left != null) q.add(temp.left);
          if(temp.right != null) q.add(temp.right);
        }
      }
      if(found == true){
        while(q.size() > 0){
          System.out.print(q.remove().data + " ");
        }
        return;
      }
    }
  }
 
  public static void main(String[] args) {
    Node 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);
 
    printCousins(root, root.left.right);
  }
}
 
// This Code is contributed by Nidhi goel.


Python3




# python program to print cousins of a node
# A binary tree node
class Node:
 
    def __init__(self, data):
        self.data = data
        self.left = self.right = None
 
 
 
# function prints the cousins of a given node
def printCousins(root, node):
    # base condition
    if root == None:
        return
    # initializing bool function to track target node
    # is found or not
    found = False
    # intializing queue to perform level order traversal
    q = []
    q.append(root)
    while(len(q) > 0):
        n = len(q)
        for i in range(n):
            temp = q[0]
            q.pop(0)
            if temp.left == node or temp.right == node:
                found = True
            else:
                if(temp.left):
                    q.append(temp.left)
                if(temp.right):
                    q.append(temp.right)
 
        if found:
            while(len(q) > 0):
                print(q.pop(0).data)
            return
 
# driver code to test above function
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)
 
printCousins(root, root.left.right)
 
# The code is contributed by Nidhi goel.


C#




// C# program to print cousins of a node
using System;
using System.Collections.Generic;
 
public class GfG
{
 
  // A Binary Tree Node
  class Node
  {
    public int data;
    public Node left, right;
  }
 
  // A utility function to create 
  // a new Binary Tree Node
  static Node newNode(int item)
  {
    Node temp = new Node();
    temp.data = item;
    temp.left = null;
    temp.right = null;
    return temp;
  }
 
  // function prints the cousins of a given node
  static void printCousins(Node root, Node node){
    // base condition
    if(root == null)
      return;
    // initializing bool function to track target node
    // is found or not
    bool found = false;
    // initializing queue to perform level order traversal
    Queue<Node> q = new Queue<Node>();
    q.Enqueue(root);
    while(q.Count!=0){
      int n = q.Count;
      for(int i = 0; i<n; i++){
        Node temp = q.Dequeue();
        if(temp.left == node || temp.right == node){
          found = true;
        }
        else{
          if(temp.left!=null)
            q.Enqueue(temp.left);
          if(temp.right!=null)
            q.Enqueue(temp.right);
        }
      }
      if(found){
        while(q.Count!=0){
          Node temp=q.Dequeue();
          Console.Write(temp.data+" ");
        }
        Console.WriteLine();
        return;
      }
    }
  }
 
  // Driver Code to test above function
  public static void Main(String[] args)
  {
    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);
 
    printCousins(root, root.left.right);
 
  }
}


Javascript




// JavaScript program to print cousins of a node
// A binary tree node
// THIS CODE IS CONTRIBUTED BY KIRTI AGARWAL(KIRTIAGARWAL23121999)
class Node{
    constructor(data){
        this.data = data;
        this.left = this.right = null;
    }
}
 
// return a new tree node
function newNode(data){
    return new Node(data);
}
 
// function prints the cousins of a given node
function printCousins(root, node){
    // base condition
    if(root == null) return
    // initializing bool function to track target node
    // is found or not
    let found = false;
    // initializing queue to perform level order traversal
    let q = [];
    q.push(root);
    while(q.length > 0){
        let n = q.length;
        for(let i = 0; i<n; i++){
            let temp = q.shift();
            if(temp.left == node || temp.right == node){
                found = true;
            }
            else{
                if(temp.left) q.push(temp.left);
                if(temp.right) q.push(temp.right);
            }
        }
        if(found){
            while(q.length > 0){
                document.write(q.shift().data);
            }
            return;
        }
    }
}
 
// driver code to test above function
let 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);
 
printCousins(root, root.left.right);


Output

6 7 

Time Complexity: O(N) where N is the number of nodes in a given binary tree.
Auxiliary Space: O(N) due to queue data structure.

Can we solve this problem using single traversal? Please refer below article 
Print cousins of a given node in Binary Tree | Single Traversal



Last Updated : 20 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads