Find Sibling node of a given node value in Binary Tree

Question:

Given a binary tree root node and a node value, get the sibling of that node.

Solution:

If the input node value is 10, its sibling is 25
If the input node value is 7, its sibling is 15
If the input node value is 16, its sibling is NULL

We can solve this problem by traversing in pre order.

Steps:

1. from the parent node, check if any of it’s children node value is matching.
2. If it is matching, then return the other sibling value if present
3. If the value is not matching, then call recursively theleft child and the right child.

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;
    }
};

Node* get_sibling(Node *node, int key) 
{
    if (node == NULL || node->data == key) 
    {
      return NULL;
    }

    if (node->left != NULL && node->left->data == key) 
    {
      return node->right;
    }
    
    if (node->right != NULL && node->right->data == key) 
    {
      return node->left;
    }

    Node *temp = get_sibling(node->left, key);

    if (temp != NULL) 
    {
      return temp;
    }

    temp = get_sibling(node->right, key);
    return temp;
}

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 = 7;
    Node *sibling = get_sibling(root, child);

    if (sibling != NULL)
    {
        cout<<"The sibling of "<<child<<" is " << sibling->data<<endl;
    } else {
        cout<< child<<" does not have any sibling"<<endl;
    }

    return 0;  
}  

Output:

The sibling of 7 is 15

Previous Article

Check if given Binary Tree is BST

Next Article

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

Write a Comment

Leave a Comment

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