Cousins of a Given Node in Binary Tree

Last Updated : 4 Jul, 2026

Given the root of a binary tree and a node, return all cousins (not siblings) of the given node in the order of their appearance. If no cousins exist, return [-1].

Examples: 

Input: root[] = [1, 2, 3, 4, 5, 6, 7], node = 5

12345678

Output: [6, 7]
Explanation: Node 5 is at the same level as nodes 4, 6, and 7.
Among them, node 4 is a sibling of 5 since both have the same parent (2), so it is not considered a cousin.
Nodes 6 and 7 have a different parent (3), making them cousins of node 5. Therefore, the output is 6 7.

Input: root[] = [9, 5, N], node = 5
9
/
5
Output: [-1]
Explanation: There are no other nodes at the same level as node 5. Therefore, the output is [-1].

Try It Yourself
redirect icon

[Naive Approach] Using Two DFS Traversals - O(n) Time and O(h) Space

The idea is to first perform a DFS to find the level and parent of the given node. Then perform another DFS to visit every node again. Whenever a node is found at the target level with a different parent, add it to the answer. If no such node exists, return [-1].

Working of the Approach:

  • Perform a DFS to find the level and parent of the given target node.
  • Traverse the tree again using DFS and visit every node. If a node is at the same level as the target and has a different parent, add it to the answer.
  • Ignore nodes that share the same parent as the target since they are siblings, not cousins.
  • After the traversal, if no cousin is found, return [-1]; otherwise, return the collected cousin nodes.
C++
#include <iostream>
#include <vector>
using namespace std;

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

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

// Find the level and parent of the target node
void findNode(Node *root, Node *parent, Node *target, int level, int &targetLevel, Node *&targetParent)
{
    if (root == nullptr)
        return;

    // Target node found
    if (root == target)
    {
        targetLevel = level;
        targetParent = parent;
        return;
    }

    // Search in left subtree
    findNode(root->left, root, target, level + 1, targetLevel, targetParent);

    // Search in right subtree
    findNode(root->right, root, target, level + 1, targetLevel, targetParent);
}

// Collect all cousin nodes
void findCousins(Node *root, Node *parent, int level, int targetLevel, Node *targetParent, vector<int> &ans)
{
    if (root == nullptr)
        return;

    // If current node is at target level
    if (level == targetLevel)
    {
        // Ignore siblings of the target node
        if (parent != targetParent)
            ans.push_back(root->data);

        return;
    }

    // Traverse left subtree
    findCousins(root->left, root, level + 1, targetLevel, targetParent, ans);

    // Traverse right subtree
    findCousins(root->right, root, level + 1, targetLevel, targetParent, ans);
}

vector<int> getCousins(Node *root, Node *node)
{
    // Root has no cousins
    if (root == node)
        return {-1};

    int targetLevel = -1;
    Node *targetParent = nullptr;

    // Find the level and parent of target node
    findNode(root, nullptr, node, 0, targetLevel, targetParent);

    vector<int> ans;

    // Collect all cousin nodes
    findCousins(root, nullptr, 0, targetLevel, targetParent, ans);

    // No cousins exist
    if (ans.empty())
        return {-1};

    return ans;
}

int main()
{
    // Construct the binary tree
    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->right->left = new Node(6);
    root->right->right = new Node(7);

    Node *node = root->left->right;

    vector<int> ans = getCousins(root, node);

    cout << "[";

    for (int i = 0; i < ans.size(); i++)
    {
        cout << ans[i];

        if (i + 1 < ans.size())
            cout << ", ";
    }

    cout << "]";

    return 0;
}
Java
import java.util.*;

class Node {
    int data;
    Node left;
    Node right;

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

public class GFG {

    // Find the level and parent of the target node
    static void findNode(Node root, Node parent,
                         Node target, int level,
                         int[] targetLevel,
                         Node[] targetParent)
    {

        if (root == null)
            return;

        // Target node found
        if (root == target) {
            targetLevel[0] = level;
            targetParent[0] = parent;
            return;
        }

        // Search in left subtree
        findNode(root.left, root, target, level + 1,
                 targetLevel, targetParent);

        // Search in right subtree
        findNode(root.right, root, target, level + 1,
                 targetLevel, targetParent);
    }

    // Collect all cousin nodes
    static void findCousins(Node root, Node parent,
                            int level, int targetLevel,
                            Node targetParent,
                            ArrayList<Integer> ans)
    {

        if (root == null)
            return;

        // If current node is at target level
        if (level == targetLevel) {

            // Ignore siblings of the target node
            if (parent != targetParent)
                ans.add(root.data);

            return;
        }

        // Traverse left subtree
        findCousins(root.left, root, level + 1, targetLevel,
                    targetParent, ans);

        // Traverse right subtree
        findCousins(root.right, root, level + 1,
                    targetLevel, targetParent, ans);
    }

    static ArrayList<Integer> getCousins(Node root,
                                         Node node)
    {

        // Root has no cousins
        if (root == node)
            return new ArrayList<>(Arrays.asList(-1));

        int[] targetLevel = { -1 };
        Node[] targetParent = { null };

        // Find the level and parent of target node
        findNode(root, null, node, 0, targetLevel,
                 targetParent);

        ArrayList<Integer> ans = new ArrayList<>();

        // Collect all cousin nodes
        findCousins(root, null, 0, targetLevel[0],
                    targetParent[0], ans);

        // No cousins exist
        if (ans.isEmpty())
            return new ArrayList<>(Arrays.asList(-1));

        return ans;
    }

    public static void main(String[] args)
    {

        // Construct the binary tree
        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.right.left = new Node(6);
        root.right.right = new Node(7);

        Node node = root.left.right;

        ArrayList<Integer> ans = getCousins(root, node);

        System.out.print("[");

        for (int i = 0; i < ans.size(); i++) {
            System.out.print(ans.get(i));

            if (i + 1 < ans.size())
                System.out.print(", ");
        }

        System.out.println("]");
    }
}
Python
class Node:
    def __init__(self, val):
        self.data = val
        self.left = None
        self.right = None

# Find the level and parent of the target node


def findNode(root, parent, target, level, targetLevel, targetParent):
    if not root:
        return

    # Target node found
    if root == target:
        targetLevel[0] = level
        targetParent[0] = parent
        return

    # Search in left subtree
    findNode(root.left, root, target, level + 1, targetLevel, targetParent)

    # Search in right subtree
    findNode(root.right, root, target, level + 1, targetLevel, targetParent)

# Collect all cousin nodes


def findCousins(root, parent, level, targetLevel, targetParent, ans):
    if not root:
        return

    # If current node is at target level
    if level == targetLevel:
        # Ignore siblings of the target node
        if parent != targetParent:
            ans.append(root.data)

        return

    # Traverse left subtree
    findCousins(root.left, root, level + 1, targetLevel, targetParent, ans)

    # Traverse right subtree
    findCousins(root.right, root, level + 1, targetLevel, targetParent, ans)


def getCousins(root, node):
    # Root has no cousins
    if root == node:
        return [-1]

    targetLevel = [-1]
    targetParent = [None]

    # Find the level and parent of target node
    findNode(root, None, node, 0, targetLevel, targetParent)

    ans = []

    # Collect all cousin nodes
    findCousins(root, None, 0, targetLevel[0], targetParent[0], ans)

    # No cousins exist
    if not ans:
        return [-1]

    return ans


if __name__ == '__main__':
    # Construct the binary tree
    root = Node(1)
    root.left = Node(2)
    root.right = Node(3)
    root.left.left = Node(4)
    root.left.right = Node(5)
    root.right.left = Node(6)
    root.right.right = Node(7)

    node = root.left.right

    ans = getCousins(root, node)

    print('[', end='')

    for i in range(len(ans)):
        print(ans[i], end='')

        if i + 1 < len(ans):
            print(', ', end='')

    print(']')
C#
using System;
using System.Collections.Generic;

class Node {
    public int data;
    public Node left;
    public Node right;

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

class GFG {
    // Find the level and parent of the target node
    void FindNode(Node root, Node parent, Node target,
                  int level, ref int targetLevel,
                  ref Node targetParent)
    {
        if (root == null)
            return;

        // Target node found
        if (root == target) {
            targetLevel = level;
            targetParent = parent;
            return;
        }

        // Search in left subtree
        FindNode(root.left, root, target, level + 1,
                 ref targetLevel, ref targetParent);

        // Search in right subtree
        FindNode(root.right, root, target, level + 1,
                 ref targetLevel, ref targetParent);
    }

    // Collect all cousin nodes
    void FindCousins(Node root, Node parent, int level,
                     int targetLevel, Node targetParent,
                     List<int> ans)
    {
        if (root == null)
            return;

        // If current node is at target level
        if (level == targetLevel) {
            // Ignore siblings of the target node
            if (parent != targetParent)
                ans.Add(root.data);

            return;
        }

        // Traverse left subtree
        FindCousins(root.left, root, level + 1, targetLevel,
                    targetParent, ans);

        // Traverse right subtree
        FindCousins(root.right, root, level + 1,
                    targetLevel, targetParent, ans);
    }

    public List<int> getCousins(Node root, Node node)
    {
        // Root has no cousins
        if (root == node)
            return new List<int>{ -1 };

        int targetLevel = -1;
        Node targetParent = null;

        // Find the level and parent of target node
        FindNode(root, null, node, 0, ref targetLevel,
                 ref targetParent);

        List<int> ans = new List<int>();

        // Collect all cousin nodes
        FindCousins(root, null, 0, targetLevel,
                    targetParent, ans);

        // No cousins exist
        if (ans.Count == 0)
            return new List<int>{ -1 };

        return ans;
    }

    static void Main()
    {
        // Construct the binary tree
        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.right.left = new Node(6);
        root.right.right = new Node(7);

        Node node = root.left.right;

        GFG obj = new GFG();
        List<int> ans = obj.getCousins(root, node);

        Console.Write("[");

        for (int i = 0; i < ans.Count; i++) {
            Console.Write(ans[i]);

            if (i + 1 < ans.Count)
                Console.Write(", ");
        }

        Console.WriteLine("]");
    }
}
JavaScript
class Node {
    constructor(val)
    {
        this.data = val;
        this.left = null;
        this.right = null;
    }
}

// Find the level and parent of the target node
function findNode(root, parent, target, level, targetInfo)
{
    if (root === null)
        return;

    // Target node found
    if (root.data === target) {
        targetInfo.level = level;
        targetInfo.parent = parent ? parent.data : null;
        return;
    }

    // Search in left subtree
    findNode(root.left, root, target, level + 1,
             targetInfo);

    // Search in right subtree
    findNode(root.right, root, target, level + 1,
             targetInfo);
}

// Collect all cousin nodes
function findCousins(root, parent, level, targetLevel,
                     targetParent, ans)
{
    if (root === null)
        return;

    // If current node is at target level
    if (level === targetLevel) {

        // Ignore siblings of the target node
        if ((parent ? parent.data : null) !== targetParent)
            ans.push(root.data);

        return;
    }

    // Traverse left subtree
    findCousins(root.left, root, level + 1, targetLevel,
                targetParent, ans);

    // Traverse right subtree
    findCousins(root.right, root, level + 1, targetLevel,
                targetParent, ans);
}

function getCousins(root, node)
{

    // Root has no cousins
    if (root.data === node)
        return [ -1 ];

    let targetInfo = {level : -1, parent : null};

    // Find the level and parent of target node
    findNode(root, null, node, 0, targetInfo);

    let ans = [];

    // Collect all cousin nodes
    findCousins(root, null, 0, targetInfo.level,
                targetInfo.parent, ans);

    // No cousins exist
    if (ans.length === 0)
        return [ -1 ];

    return ans;
}

// Construct the binary tree
let 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.right.left = new Node(6);
root.right.right = new Node(7);

let node = 5;

let ans = getCousins(root, node);

process.stdout.write("[");

for (let i = 0; i < ans.length; i++) {
    process.stdout.write(ans[i].toString());

    if (i + 1 < ans.length)
        process.stdout.write(", ");
}

process.stdout.write("]");

Output
[6, 7]

[Expected Approach] Using Single Level Order Traversal - O(n) Time and O(n) Space

The idea is to perform a single level order traversal of the binary tree. While processing each level, check whether the current node is the parent of the target node. If it is, skip adding both the target node and its sibling to the queue. Otherwise, insert its children normally. After completing that level, the queue contains only the cousins of the target node.

Let us understand with an example:
Input: root[] = [1, 2, 3, 4, 5, 6, 7], node = 5

  • Start the level order traversal from the root node 1. Since it is not the parent of the target node 5, add its children 2 and 3 to the queue.
  • Process the next level containing 2 and 3. Node 2 is the parent of 5, so do not add its children (4 and 5) to the queue. For node 3, add its children 6 and 7 to the queue.
  • After completing this level, the parent of the target node has been found, so stop the traversal.
  • The queue now contains only 6 and 7, which are the nodes at the same level as 5 but have a different parent.
  • Return [6, 7] as the cousins of the given node.
C++
#include <iostream>
#include <queue>
#include <vector>
using namespace std;

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

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

vector<int> getCousins(Node *root, Node *node)
{
    vector<int> ans;

    // Root has no cousins
    if (root == node)
    {
        ans.push_back(-1);
        return ans;
    }

    queue<Node *> q;
    bool found = false;

    q.push(root);

    // Traverse the tree level by level
    while (!q.empty() && !found)
    {
        int size_ = q.size();

        while (size_--)
        {
            Node *curr = q.front();
            q.pop();

            // If current node is the parent of target node,
            // skip adding the target node and its sibling
            if (curr->left == node || curr->right == node)
            {
                found = true;
            }
            else
            {
                // Push left child
                if (curr->left)
                    q.push(curr->left);

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

    // Remaining nodes in the queue are cousins
    if (!q.empty())
    {
        while (!q.empty())
        {
            ans.push_back(q.front()->data);
            q.pop();
        }
    }
    else
    {
        ans.push_back(-1);
    }

    return ans;
}

int main()
{
    // Construct the binary tree
    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->right->left = new Node(6);
    root->right->right = new Node(7);

    Node *node = root->left->right;

    vector<int> ans = getCousins(root, node);

    cout << "[";

    for (int i = 0; i < ans.size(); i++)
    {
        cout << ans[i];

        if (i + 1 < ans.size())
            cout << ", ";
    }

    cout << "]";

    return 0;
}
Java
import java.util.*;

class Node {
    int data;
    Node left;
    Node right;

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

public class GFG {

    static ArrayList<Integer> getCousins(Node root,
                                         Node node)
    {

        ArrayList<Integer> ans = new ArrayList<>();

        // Root has no cousins
        if (root == node) {
            ans.add(-1);
            return ans;
        }

        Queue<Node> q = new LinkedList<>();
        boolean found = false;

        q.offer(root);

        // Traverse the tree level by level
        while (!q.isEmpty() && !found) {

            int size_ = q.size();

            while (size_-- > 0) {

                Node curr = q.poll();

                // If current node is the parent of target
                // node, skip adding the target node and its
                // sibling
                if (curr.left == node
                    || curr.right == node) {
                    found = true;
                }
                else {

                    // Push left child
                    if (curr.left != null)
                        q.offer(curr.left);

                    // Push right child
                    if (curr.right != null)
                        q.offer(curr.right);
                }
            }
        }

        // Remaining nodes in the queue are cousins
        if (!q.isEmpty()) {

            while (!q.isEmpty()) {
                ans.add(q.poll().data);
            }
        }
        else {
            ans.add(-1);
        }

        return ans;
    }

    public static void main(String[] args)
    {

        // Construct the binary tree
        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.right.left = new Node(6);
        root.right.right = new Node(7);

        Node node = root.left.right;

        ArrayList<Integer> ans = getCousins(root, node);

        System.out.print("[");

        for (int i = 0; i < ans.size(); i++) {
            System.out.print(ans.get(i));

            if (i + 1 < ans.size())
                System.out.print(", ");
        }

        System.out.print("]");
    }
}
Python
from collections import deque


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


def getCousins(root, node):
    ans = []

    # Root has no cousins
    if root == node:
        ans.append(-1)
        return ans

    q = deque()
    found = False

    q.append(root)

    # Traverse the tree level by level
    while q and not found:
        size_ = len(q)

        for _ in range(size_):
            curr = q.popleft()

            # If current node is the parent of target node,
            # skip adding the target node and its sibling
            if curr.left == node or curr.right == node:
                found = True
            else:
                # Push left child
                if curr.left is not None:
                    q.append(curr.left)

                # Push right child
                if curr.right is not None:
                    q.append(curr.right)

    # Remaining nodes in the queue are cousins
    if q:
        while q:
            ans.append(q.popleft().data)
    else:
        ans.append(-1)

    return ans


if __name__ == "__main__":
    # Construct the binary tree
    root = Node(1)
    root.left = Node(2)
    root.right = Node(3)
    root.left.left = Node(4)
    root.left.right = Node(5)
    root.right.left = Node(6)
    root.right.right = Node(7)

    node = root.left.right

    ans = getCousins(root, node)

    print('[', end='')
    for i in range(len(ans)):
        print(ans[i], end='')
        if i + 1 < len(ans):
            print(', ', end='')
    print(']')
C#
using System;
using System.Collections.Generic;

class Node {
    public int data;
    public Node left;
    public Node right;

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

class GFG {
    static List<int> getCousins(Node root, Node node)
    {
        List<int> ans = new List<int>();

        // Root has no cousins
        if (root == node) {
            ans.Add(-1);
            return ans;
        }

        Queue<Node> q = new Queue<Node>();
        bool found = false;

        q.Enqueue(root);

        // Traverse the tree level by level
        while (q.Count > 0 && !found) {
            int size_ = q.Count;

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

                // If current node is the parent of target
                // node, skip adding the target node and its
                // sibling
                if (curr.left == node
                    || curr.right == node) {
                    found = true;
                }
                else {
                    // Push left child
                    if (curr.left != null)
                        q.Enqueue(curr.left);

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

        // Remaining nodes in the queue are cousins
        if (q.Count > 0) {
            while (q.Count > 0) {
                ans.Add(q.Dequeue().data);
            }
        }
        else {
            ans.Add(-1);
        }

        return ans;
    }

    static void Main()
    {
        // Construct the binary tree
        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.right.left = new Node(6);
        root.right.right = new Node(7);

        Node node = root.left.right;

        List<int> ans = getCousins(root, node);

        Console.Write("[");

        for (int i = 0; i < ans.Count; i++) {
            Console.Write(ans[i]);

            if (i + 1 < ans.Count)
                Console.Write(", ");
        }

        Console.Write("]");
    }
}
JavaScript
class Node {
    constructor(val)
    {
        this.data = val;
        this.left = null;
        this.right = null;
    }
}

function getCousins(root, node)
{
    let ans = [];

    // Root has no cousins
    if (root === node) {
        ans.push(-1);
        return ans;
    }

    let q = [];
    let found = false;

    q.push(root);

    // Traverse the tree level by level
    while (q.length > 0 && !found) {
        let size_ = q.length;

        for (let i = 0; i < size_; i++) {
            let curr = q.shift();

            // If current node is the parent of target node,
            // skip adding the target node and its sibling
            if (curr.left === node || curr.right === node) {
                found = true;
            }
            else {
                // Push left child
                if (curr.left !== null) {
                    q.push(curr.left);
                }

                // Push right child
                if (curr.right !== null) {
                    q.push(curr.right);
                }
            }
        }
    }

    // Remaining nodes in the queue are cousins
    if (q.length > 0) {
        while (q.length > 0) {
            ans.push(q[0].data);
            q.shift();
        }
    }
    else {
        ans.push(-1);
    }

    return ans;
}

// Construct the binary tree
let 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.right.left = new Node(6);
root.right.right = new Node(7);

let node = root.left.right;

let ans = getCousins(root, node);

console.log("[");
for (let i = 0; i < ans.length; i++) {
    console.log(ans[i]);
    if (i + 1 < ans.length) {
        console.log(", ");
    }
}
console.log("]");

Output
[6, 7]
Comment