Check if two nodes are cousins in a Binary Tree

Last Updated : 7 Jul, 2026

Given the root of a binary tree with distinct node values and two integers a and b, check whether the nodes with values a and b are cousins.

Note: Two nodes are cousins if they are at the same depth but have different parents.

Example: 

Input: root = [1, 2, 3], a = 2, b = 3
Split-array-into-three-equal-sum-segments-38Output: false
Explanation: Here, nodes 2 and 3 are at the same level but have same parent nodes.

Input: root = [1, 2, 3, 5, N, N, 4], a = 5, b = 4

Split-array-into-three-equal-sum-segments-39

Output: true
Explanation: Here, nodes 5 and 4 are at the same level and have different parent nodes. Hence, they both are cousins.

Input: root = [10, 5, 15, 3, 7, 12, 20], a = 7, b = 12

Split-array-into-three-equal-sum-segments-40

Output: true
Explanation: Here, nodes 7 and 12 are at the same level and have different parent nodes. Hence, they both are cousins.

Try It Yourself
redirect icon

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.

C++
#include <iostream>

using namespace std;

class Node {
  public:
    int data;
    Node* left, *right;

    Node(int x) {
        data = x;
        left = right = nullptr;
    }
};

// Recursive function to check if two Nodes are siblings
bool areSiblings(Node* root, int a, int b) {

    // Base case
    if (root == nullptr)
        return false;

    if (root->left != nullptr && root->right != nullptr &&
        root->left->data == a && root->right->data == b)
        return true;

    if (root->left != nullptr && root->right != nullptr &&
        root->left->data == b && root->right->data == a)
        return true;

    return areSiblings(root->left, a, b) ||
           areSiblings(root->right, a, b);
}

// Recursive function to find level of Node with data = value
int level(Node* root, int value, int lev) {

    // Base cases
    if (root == nullptr)
        return 0;
    if (root->data == value)
        return lev;

    // Return level if Node is present in left subtree
    int l = level(root->left, value, lev + 1);
    if (l != 0)
        return l;

    // Else search in right subtree
    return level(root->right, value, lev + 1);
}

// Returns true if a and b are cousins, otherwise false
bool areCousins(Node* root, int a, int b) {

    // Cousins must be at the same level and have different parents.
    if (a == b)
        return false;

    int aLevel = level(root, a, 1);
    int bLevel = level(root, b, 1);

    // If either node does not exist in the tree
    if (aLevel == 0 || bLevel == 0)
        return false;

    return (aLevel == bLevel && !areSiblings(root, a, b));
}

int main() {

    Node* root = new Node(1);
    root->left = new Node(2);
    root->right = new Node(3);
    root->left->left = new Node(4);
    root->right->right = new Node(5);

    int a = 4, b = 5;

    if (areCousins(root, a, b))
        cout << "true\n";
    else
        cout << "false\n";

    return 0;
}
C
// C program to 
// check if two Nodes are Cousins
#include <stdio.h>
#include <stdlib.h>

struct Node {
    int data;
    struct Node* left, *right;
};

// Recursive function to check if two Nodes are siblings
int areSiblings(struct Node* root, int a, int b) {
    
    // Base case
    if (root == NULL)
        return 0;

    if (root->left != NULL && root->right != NULL &&
        root->left->data == a && root->right->data == b)
        return 1;
        
    if (root->left != NULL && root->right != NULL &&
        root->left->data == b && root->right->data == a)
        return 1;
        
    return areSiblings(root->left, a, b) ||
           areSiblings(root->right, a, b);
}

// Recursive function to find level of 
// Node with data = value in a binary tree
int level(struct Node* root, int value, int lev) {
    
    // base cases
    if (root == NULL)
        return 0;
    if (root->data == value)
        return lev;

    // Return level if Node is 
    // present in left subtree
    int l = level(root->left, value, lev + 1);
    if (l != 0)
        return l;

    // Else search in right subtree
    return level(root->right, value, lev + 1);
}

// Returns true if a and b are cousins, otherwise false
int areCousins(struct Node* root, int a, int 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) 
        return 0;
    
    int aLevel = level(root, a, 1);
    int bLevel = level(root, b, 1);
    
    // if a or b does not exist in the tree
    if (aLevel == 0 || bLevel == 0) 
        return 0;
        
    if (aLevel == bLevel && !areSiblings(root, a, b))
        return 1;
    else
        return 0;
}

struct Node* createNode(int x) {
    struct Node* newNode = 
    (struct Node*)malloc(sizeof(struct Node));
    newNode->data = x;
    newNode->left = newNode->right = NULL;
    return newNode;
}

int main() {

    struct Node* root = createNode(1);
    root->left = createNode(2);
    root->right = createNode(3);
    root->left->left = createNode(4);
    root->right->right = createNode(5);
    
    int a = 4, b = 5;
    
    if (areCousins(root, a, b)) {
        printf("true\n");
    }
    else {
        printf("false\n");
    }

    return 0;
}
Java
// Java program to 
// check if two Nodes are Cousins
class Node {
    int data;
    Node left, right;
    
    Node(int x) {
        data = x;
        left = right = null;
    }
}

class GFG {
    
    // Recursive function to check if 
    // two Nodes are siblings
    static boolean areSiblings(Node root, int a, int b) {
        
        // Base case
        if (root == null)
            return false;

        if (root.left != null && root.right != null &&
            root.left.data == a && root.right.data == b)
            return true;
            
        if (root.left != null && root.right != null &&
            root.left.data == b && root.right.data == a)
            return true;
            
        return areSiblings(root.left, a, b) ||
               areSiblings(root.right, a, b);
    }

    // Recursive function to find level of Node with 
  	// data = value in a binary tree
    static int level(Node root, int value, int lev) {
        
        // base cases
        if (root == null)
            return 0;
        if (root.data == value)
            return lev;

        // Return level if Node is present in left subtree
        int l = level(root.left, value, lev + 1);
        if (l != 0)
            return l;

        // Else search in right subtree
        return level(root.right, value, lev + 1);
    }

    // Returns true if a and b are cousins, otherwise false
    static boolean areCousins(Node root, int a, int 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) 
            return false;
        
        int aLevel = level(root, a, 1);
        int bLevel = level(root, b, 1);
        
        // if a or b does not exist in the tree
        if (aLevel == 0 || bLevel == 0) 
            return false;
            
        return aLevel == bLevel && !areSiblings(root, a, b);
    }

    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.right.right = new Node(5);
        
        int a = 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 cousins

class Node:
    def __init__(self, x):
        self.data = x
        self.left = self.right = None

# Recursive function to check 
# if two Nodes are siblings
def areSiblings(root, a, b):
    
    # Base case
    if root is None:
        return False

    if root.left is not None and root.right is not None and \
       root.left.data == a and root.right.data == b:
        return True
        
    if root.left is not None and root.right is not None and \
       root.left.data == b and root.right.data == a:
        return True
        
    return areSiblings(root.left, a, b) or areSiblings(root.right, a, b)

# Recursive function to find level of Node with 
# data = value in a binary tree
def level(root, value, lev):
    
    # base cases
    if root is None:
        return 0
    if root.data == value:
        return lev

    # Return level if Node is present in left subtree
    l = level(root.left, value, lev + 1)
    if l != 0:
        return l

    # Else search in right subtree
    return level(root.right, value, lev + 1)

# Returns true if a and b are cousins, otherwise false
def areCousins(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:
        return False
    
    aLevel = level(root, a, 1)
    bLevel = level(root, b, 1)
    
    # if a or b does not exist in the tree
    if aLevel == 0 or bLevel == 0:
        return False
        
    return aLevel == bLevel and not areSiblings(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, 5
    
    if areCousins(root, a, b):
        print("true")
    else:
        print("false")
C#
// C# program to 
// check if two Nodes are Cousins
using System;

class Node {
    public int data;
    public Node left, right;
    
    public Node(int x) {
        data = x;
        left = right = null;
    }
}

class GFG {
    
    // Recursive function to check 
    // if two Nodes are siblings
    static bool areSiblings(Node root, int a, int b) {
        
        // Base case
        if (root == null)
            return false;

        if (root.left != null && root.right != null &&
            root.left.data == a && root.right.data == b)
            return true;
            
        if (root.left != null && root.right != null &&
            root.left.data == b && root.right.data == a)
            return true;
            
        return areSiblings(root.left, a, b) ||
               areSiblings(root.right, a, b);
    }

    // Recursive function to find level of 
    // Node with data = value in a binary tree
    static int Level(Node root, int value, int lev) {
        
        // base cases
        if (root == null)
            return 0;
        if (root.data == value)
            return lev;

        // Return level if Node is present in left subtree
        int l = Level(root.left, value, lev + 1);
        if (l != 0)
            return l;

        // Else search in right subtree
        return Level(root.right, value, lev + 1);
    }

    // Returns true if a and b are cousins, otherwise false
    static bool areCousins(Node root, int a, int 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) 
            return false;
        
        int aLevel = Level(root, a, 1);
        int bLevel = Level(root, b, 1);
        
        // if a or b does not exist in the tree
        if (aLevel == 0 || bLevel == 0) 
            return false;
            
        return aLevel == bLevel && !areSiblings(root, a, b);
    }

    static void Main() {
        
        Node root = new Node(1);
        root.left = new Node(2);
        root.right = new Node(3);
        root.left.left = new Node(4);
        root.right.right = new Node(5);
        
        int a = 4, b = 5;
        
        if (areCousins(root, a, b)) {
            Console.WriteLine("true");
        }
        else {
            Console.WriteLine("false");
        }
    }
}
JavaScript
// JavaScript program to 
// check if two Nodes are Cousins
class Node {
    constructor(x) {
        this.data = x;
        this.left = this.right = null;
    }
}

// Recursive function to check if two Nodes are siblings
function areSiblings(root, a, b) {
    
    // Base case
    if (root == null)
        return false;

    if (root.left != null && root.right != null &&
        root.left.data === a && root.right.data === b)
        return true;
        
    if (root.left != null && root.right != null &&
        root.left.data === b && root.right.data === a)
        return true;
        
    return areSiblings(root.left, a, b) || 
           areSiblings(root.right, a, b);
}

// Recursive function to find level of Node with 
// data = value in a binary tree
function level(root, value, lev) {
    
    // base cases
    if (root == null)
        return 0;
    if (root.data === value)
        return lev;

    // Return level if Node is present in left subtree
    let l = level(root.left, value, lev + 1);
    if (l !== 0)
        return l;

    // Else search in right subtree
    return level(root.right, value, lev + 1);
}

// Returns true if a and b are cousins, otherwise false
function areCousins(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) 
        return false;
    
    let aLevel = level(root, a, 1);
    let bLevel = level(root, b, 1);
    
    // if a or b does not exist in the tree
    if (aLevel === 0 || bLevel === 0)
        return false;
        
    return aLevel === bLevel && !areSiblings(root, a, b);
}
let root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.right.right = new Node(5);

let a = 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 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.

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>
using namespace std;

// Structure of a binary tree node
class Node {
  public:
    int data;
    Node *left, *right;

    Node(int x) {
        data = x;
        left = right = nullptr;
    }
};

// Function to check if two nodes are cousins
bool areCousins(Node* root, int a, int b) {

    // Empty tree or same node values cannot be cousins
    if (root == nullptr || a == b)
        return false;

    queue<Node*> q;
    q.push(root);

    while (!q.empty()) {
        int sz = q.size();

        // Track whether a and b are present at the current level
        bool aFound = 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 siblings
            if (curr->left && curr->right) {
                int left = curr->left->data;
                int right = curr->right->data;

                if ((left == a && right == b) ||
                    (left == b && right == a))
                    return false;
            }

            if (curr->left)
                q.push(curr->left);

            if (curr->right)
                q.push(curr->right);
        }

        // Both nodes found at the same level
        if (aFound && bFound)
            return true;

        // Only one node found at this level
        if (aFound || bFound)
            return false;
    }

    return false;
}

int main() {
    Node* root = new Node(1);
    root->left = new Node(2);
    root->right = new Node(3);
    root->left->left = new Node(4);
    root->right->right = new Node(5);

    int a = 4, b = 5;

    if (areCousins(root, a, b))
        cout << "true\n";
    else
        cout << "false\n";

    return 0;
}
Java
import java.util.LinkedList;
import java.util.Queue;

// Structure of a binary tree node
class Node {
  int data;
  Node left, right;

  Node(int x) {
      data = x;
      left = right = null;
  }
}

public class GFG {
  // Function to check if two nodes are cousins
  public static boolean areCousins(Node root, int a, int b) {

      // Empty tree or same node values cannot be cousins
      if (root == null || a == b)
          return false;

      Queue<Node> q = new LinkedList<>();
      q.add(root);

      while (!q.isEmpty()) {
          int sz = q.size();

          // Track whether a and b are present at the current level
          boolean aFound = false, bFound = false;

          while (sz-- > 0) {
              Node curr = q.poll();

              if (curr.data == a)
                  aFound = true;
              if (curr.data == b)
                  bFound = true;

              // If a and b have the same parent, they are siblings
              if (curr.left!= null && curr.right!= null) {
                  int left = curr.left.data;
                  int right = curr.right.data;

                  if ((left == a && right == b) ||
                      (left == b && right == a))
                      return false;
              }

              if (curr.left!= null)
                  q.add(curr.left);

              if (curr.right!= null)
                  q.add(curr.right);
          }

          // Both nodes found at the same level
          if (aFound && bFound)
              return true;

          // Only one node found at this level
          if (aFound || bFound)
              return false;
      }

      return false;
  }

  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.right.right = new Node(5);

      int a = 4, b = 5;

      if (areCousins(root, a, b))
          System.out.println("true");
      else
          System.out.println("false");
  }
}
Python
from collections import deque

# Structure of a binary tree node
class Node:
  def __init__(self, x):
      self.data = x
      self.left = None
      self.right = None

# Function to check if two nodes are cousins
def areCousins(root, a, b):

  # Empty tree or same node values cannot be cousins
  if not root or a == b:
      return False

  queue = deque([root])

  while queue:
      sz = len(queue)

      # Track whether a and b are present at the current level
      aFound = False
      bFound = False

      while sz > 0:
          sz -= 1
          curr = queue.popleft()

          if curr.data == a:
              aFound = True
          if curr.data == b:
              bFound = True

          # If a and b have the same parent, they are siblings
          if curr.left and curr.right:
              left = curr.left.data
              right = curr.right.data

              if (left == a and right == b) or (left == b and right == a):
                  return False

          if curr.left:
              queue.append(curr.left)
          if curr.right:
              queue.append(curr.right)

      # Both nodes found at the same level
      if aFound and bFound:
          return True

      # Only one node found at this level
      if aFound or bFound:
          return False

  return False

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 = 4
  b = 5

  if areCousins(root, a, b):
      print('true')
  else:
      print('false')
C#
using System;
using System.Collections.Generic;

// Structure of a binary tree node
public class Node {
  public int data;
  public Node left, right;

  public Node(int x) {
      data = x;
      left = right = null;
  }
}

public class GFG {
  // Function to check if two nodes are cousins
  public static bool areCousins(Node root, int a, int b) {

      // Empty tree or same node values cannot be cousins
      if (root == null || a == b)
          return false;

      Queue<Node> q = new Queue<Node>();
      q.Enqueue(root);

      while (q.Count > 0) {
          int sz = q.Count;

          // Track whether a and b are present at the current level
          bool aFound = false, bFound = false;

          while (sz-- > 0) {
              Node curr = q.Dequeue();

              if (curr.data == a)
                  aFound = true;
              if (curr.data == b)
                  bFound = true;

              // If a and b have the same parent, they are siblings
              if (curr.left!= null && curr.right!= null) {
                  int left = curr.left.data;
                  int right = curr.right.data;

                  if ((left == a && right == b) ||
                      (left == b && right == a))
                      return false;
              }

              if (curr.left!= null)
                  q.Enqueue(curr.left);

              if (curr.right!= null)
                  q.Enqueue(curr.right);
          }

          // Both nodes found at the same level
          if (aFound && bFound)
              return true;

          // Only one node found at this level
          if (aFound || bFound)
              return false;
      }

      return false;
  }

  public static void Main() {
      Node root = new Node(1);
      root.left = new Node(2);
      root.right = new Node(3);
      root.left.left = new Node(4);
      root.right.right = new Node(5);

      int a = 4, b = 5;

      if (areCousins(root, a, b))
          Console.WriteLine("true");
      else
          Console.WriteLine("false");
  }
}
JavaScript
class Node {
  constructor(x) {
      this.data = x;
      this.left = null;
      this.right = null;
  }
}

// Function to check if two nodes are cousins
function areCousins(root, a, b) {

  // Empty tree or same node values cannot be cousins
  if (!root || a === b)
      return false;

  let q = [root];

  while (q.length > 0) {
      let sz = q.length;

      // Track whether a and b are present at the current level
      let aFound = false, bFound = false;

      while (sz-- > 0) {
          let curr = q.shift();

          if (curr.data === a)
              aFound = true;
          if (curr.data === b)
              bFound = true;

          // If a and b have the same parent, they are siblings
          if (curr.left && curr.right) {
              let left = curr.left.data;
              let right = curr.right.data;

              if ((left === a && right === b) ||
                  (left === b && right === a))
                  return false;
          }

          if (curr.left)
              q.push(curr.left);

          if (curr.right)
              q.push(curr.right);
      }

      // Both nodes found at the same level
      if (aFound && bFound)
          return true;

      // Only one node found at this level
      if (aFound || bFound)
          return false;
  }

  return false;
}

let root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.right.right = new Node(5);

let a = 4, b = 5;

if (areCousins(root, a, b))
  console.log('true');
else
  console.log('false');

Output
true
Comment