Check if two nodes in a Binary Tree are siblings

18 Aug, 2021
Given a binary tree and two nodes, the task is to check if the nodes are siblings of each other or not.
Two nodes are said to be siblings if they are present at the same level, and their parents are same.
Examples: 
Input : 
       1
      /  \
     2    3
    / \  / \
   4   5 6  7
First node is 4 and Second node is 6.
Output : No, they are not siblings.

Input :
         1
        /  \
       5    6
      /    /  \
     7     3   4
First node is 3 and Second node is 4
Output : Yes
Approach: On observing carefully, it can be concluded that any node in a binary tree can have maximum of two child nodes. So, since the parent of two siblings must be same, so the idea is to simply traverse the tree and for every node check if the two given nodes are its children. If it is true for any node in the tree then print YES otherwise print NO.
Below is the implementation of the above approach:  
C++
Java
Python3
C#
Javascript
// C++ program to check if two nodes are// siblings #include <bits/stdc++.h>using namespace std; // Binary Tree Nodestruct Node {    int data;    Node *left, *right;}; // Utility function to create a new nodestruct Node* newNode(int data){    struct Node* node = new Node;    node->data = data;    node->left = node->right = NULL;     return (node);} // Function to find out if two nodes are siblingsbool CheckIfNodesAreSiblings(Node* root, int data_one,                             int data_two){    if (!root)        return false;     // Compare the two given nodes with    // the childrens of current node    if (root->left && root->right) {        int left = root->left->data;        int right = root->right->data;         if (left == data_one && right == data_two)            return true;        else if (left == data_two && right == data_one)            return true;    }     // Check for left subtree    if (root->left)        if(CheckIfNodesAreSiblings(root->left, data_one,                                data_two))          return true;     // Check for right subtree    if (root->right)        if(CheckIfNodesAreSiblings(root->right, data_one,                                data_two))          return true;} // Driver codeint main(){     struct Node* root = newNode(1);    root->left = newNode(2);    root->right = newNode(3);    root->left->left = newNode(4);    root->right->left = newNode(5);    root->right->right = newNode(6);    root->left->left->right = newNode(7);     int data_one = 5;    int data_two = 6;     if (CheckIfNodesAreSiblings(root, data_one, data_two))        cout << "YES";    else        cout << "NO";     return 0;}
// Java program to check if two nodes// are siblingsimport java.util.*; class GFG{ // Binary Tree Nodestatic class Node{    int data;    Node left, right;}; // Utility function to create a// new nodestatic Node newNode(int data){    Node node = new Node();    node.data = data;    node.left = node.right = null;     return (node);}static Node root = null; // Function to find out if two nodes are siblingsstatic boolean CheckIfNodesAreSiblings(Node root,                                       int data_one,                                       int data_two){    if (root == null)        return false;     // Compare the two given nodes with    // the childrens of current node    if (root.left != null && root.right != null)    {        int left = root.left.data;        int right = root.right.data;         if (left == data_one &&           right == data_two)            return true;        else if (left == data_two &&                right == data_one)            return true;    }     // Check for left subtree    if (root.left != null)        CheckIfNodesAreSiblings(root.left,                                data_one,                                data_two);     // Check for right subtree    if (root.right != null)        CheckIfNodesAreSiblings(root.right,                                data_one,                                data_two);    return true;} // Driver codepublic static void main(String[] args){    root = newNode(1);    root.left = newNode(2);    root.right = newNode(3);    root.left.left = newNode(4);    root.right.left = newNode(5);    root.right.right = newNode(6);    root.left.left.right = newNode(7);     int data_one = 5;    int data_two = 6;     if (CheckIfNodesAreSiblings(root,                                data_one,                                data_two))        System.out.print("YES");    else        System.out.print("NO");}} // This code is contributed by Rajput-Ji
# Python3 program to check if two# nodes are siblings # Binary Tree Nodeclass Node:         def __init__(self, key):                 self.data = key        self.left = None        self.right = None # Function to find out if two nodes are siblingsdef CheckIfNodesAreSiblings(root, data_one,                                  data_two):         if (root == None):        return False     # Compare the two given nodes with    # the childrens of current node    ans = False         if (root.left != None and root.right != None):        left = root.left.data        right = root.right.data                 if (left == data_one and right == data_two):            return True        elif (left == data_two and right == data_one):            return True     # Check for left subtree    if (root.left != None):        ans = ans or CheckIfNodesAreSiblings(root.left,                                       data_one,                                       data_two)                                            # Check for right subtree    if (root.right != None):        ans = ans or CheckIfNodesAreSiblings(root.right,                                       data_one,                                       data_two)             return ans    # Driver codeif __name__ == '__main__':         root = Node(1)    root.left = Node(2)    root.right = Node(3)    root.left.left = Node(4)    root.right.left = Node(5)    root.right.right = Node(6)    root.left.left.right = Node(7)     data_one = 5    data_two = 6     if (CheckIfNodesAreSiblings(root,                                data_one,                                data_two)):        print("YES")    else:        print("NO") # This code is contributed by mohit kumar 29
// C# program to check if two nodes// are siblingsusing System; // Binary Tree Nodepublic class Node{    public int data;    public Node left, right;         // Utility function to create a    // new node    public Node(int item)    {        data = item;        left = right = null;    }} class GFG{     static Node root = null; // Function to find out if two// nodes are siblingsstatic bool CheckIfNodesAreSiblings(Node root,                                    int data_one,                                    int data_two){    if (root == null)    {        return false;    }         // Compare the two given nodes with    // the childrens of current node    if (root.left != null && root.right != null)    {        int left = root.left.data;        int right = root.right.data;                 if (left == data_one && right == data_two)        {            return true;        }        else if (left == data_two && right == data_one)        {            return true;        }    }         // Check for left subtree    if (root.left != null)    {        CheckIfNodesAreSiblings(root.left, data_one,                                data_two);    }         // Check for right subtree    if (root.right != null)    {        CheckIfNodesAreSiblings(root.right, data_one,                                data_two);    }    return true;} // Driver codestatic public void Main(){    GFG.root = new Node(1);    GFG.root.left = new Node(2);    GFG.root.right = new Node(3);    GFG.root.left.left = new Node(4);    GFG.root.right.left = new Node(5);    GFG.root.right.right = new Node(6);    GFG.root.left.left.right = new Node(7);         int data_one = 5;    int data_two = 6;         if (CheckIfNodesAreSiblings(root, data_one,                                data_two))    {        Console.WriteLine("YES");    }    else    {        Console.WriteLine("NO");    }}} // This code is contributed by avanitrachhadiya2155
<script> // Javascript program to check if two nodes// are siblings // Binary Tree Nodeclass Node{    constructor(data)    {        this.data = data;        this.left = this.right = null;    }} let root = null; // Function to find out if two nodes are siblingsfunction CheckIfNodesAreSiblings(    root, data_one, data_two){    if (root == null)        return false;      // Compare the two given nodes with    // the childrens of current node    if (root.left != null && root.right != null)    {        let left = root.left.data;        let right = root.right.data;          if (left == data_one &&           right == data_two)            return true;                     else if (left == data_two &&                right == data_one)            return true;    }      // Check for left subtree    if (root.left != null)        CheckIfNodesAreSiblings(root.left,                                data_one,                                data_two);      // Check for right subtree    if (root.right != null)        CheckIfNodesAreSiblings(root.right,                                data_one,                                data_two);    return true;} // Driver coderoot = new Node(1);root.left = new Node(2);root.right = new Node(3);root.left.left = new Node(4);root.right.left = new Node(5);root.right.right = new Node(6);root.left.left.right = new Node(7); let data_one = 5;let data_two = 6; if (CheckIfNodesAreSiblings(root,                            data_one,                            data_two))    document.write("YES");else    document.write("NO"); // This code is contributed by unknown2108 </script>
YES
 
mohit kumar 29
Rajput-Ji
avanitrachhadiya2155
vaibhav tandon
unknown2108
rcrohith2011
Binary Tree
Tree
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.