Check if given two nodes are siblings to each other in Binary Tree

Question:

Given a binary tree root node and 2 node value, check if those 2 nodes are siblings.

Solution:

If we send the node value as 7 and 15, they are siblings

If we send the node value as 7 and 18 they are not siblings.

So the solution here is, for every node it can have at max 2 children.

Hence check the children of every node and check if it matches.

If matches, return true, else false.

Solution in C++

#include <iostream>
#include <queue>
#include <stack>
using namespace std;

// structure to hold binary tree node
struct Node
{
    int data;
    Node *left, *right;

    Node(int data)
    {
        this->data = data;
        this->left = this->right = nullptr;
    }
};

bool are_siblings(Node *node, int a, int b) 
{
    if (node == NULL) 
    {
      return false;
    }

    return (node->left->data == a && node->right->data == b) 
        || (node->left->data == b && node->right->data == a)
        || are_siblings(node->left, a, b)
        || are_siblings(node->right, a, b);
  }
int main()  
{  
    Node* root = nullptr;
    /* Binary tree:
              16
            /   \
           /     \
          10      25
         /  \    /  \
        /    \  /    \
       7    15 18     30

    */

    root = new Node(16);
    root->left = new Node(10);
    root->right = new Node(25);
    root->left->left = new Node(7);
    root->left->right = new Node(15);
    root->right->left = new Node(18);
    root->right->right = new Node(30);

    int child_1 = 7;
    int child_2 = 15;

    if (are_siblings(root, child_1, child_2))
    {
        cout<<child_1<< " and "<<child_2<<" are siblings "<<endl;
    } else {
        cout<<child_1 <<" and "<<child_2<<" are NOT siblings "<<endl;
    }

    return 0;  
}  

 

Output:

7 and 15 are siblings

 

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *