Sum of cousin nodes of a given node in a BST

Given a binary search tree and a number N, the task is to find the sum of the cousins of the given node N if a node with given value ‘N’ is present in the given BST otherwise print -1.

Examples:

Input: Node = 12 
Output: 40 
Cousins are 18 and 22 

Input: 19
Output: -1

Approach: Given below is the algorithm to solve the problem.

  • Find the parent of the given node, if the node is not present return -1.
  • Traverse in the tree, find the level of each node while traversal.
  • If the level is the same as the given node. Check for the parent of that node, if the parent is different then add the node to the sum.

Below is the implementation of above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to find the sum of cousins
// of a node of a given BST
#include <bits/stdc++.h>
using namespace std;
  
// structure to store the binary tree
struct Tree {
    int data;
    struct Tree *left, *right;
};
  
// insertion of node in the binary tree
struct Tree* newNode(int data)
{
    // allocates memory
    struct Tree* node = (struct Tree*)malloc(sizeof(struct Tree));
  
    // initializes data
    node->data = data;
  
    // marks the left and right
    // child as NULL
    node->left = node->right = NULL;
  
    // Return the node after allocating memory
    return (node);
};
  
// Function which calculates the sum of the cousin Node
int SumOfCousin(struct Tree* root, int p,
                int level1, int level)
{
    int sum = 0;
    if (root == NULL)
        return 0;
  
    // nodes which has same parent
    // as the given node will not be
    // taken to count for calculation
    if (p == root->data)
        return 0;
  
    // if the level is same
    // then it is a cousin
    // as parent checking has been
    // done above
    if (level1 == level)
        return root->data;
  
    // traverse in the tree left and right
    else
        sum += SumOfCousin(root->left, p, level1 + 1, level) + SumOfCousin(root->right, p, level1 + 1, level);
  
    return sum;
}
  
// Function that returns the parent node
int ParentNode(struct Tree* root, int NodeData)
{
    int parent = -1;
  
    // traverse the full Binary tree
    while (root != NULL) {
  
        // if node is found
        if (NodeData == root->data)
            break;
  
        // if less than move to left
        else if (NodeData < root->data) {
            parent = root->data;
            root = root->left;
        }
  
        // if greater than move to rigth
        else {
            parent = root->data;
            root = root->right;
        }
    }
  
    // Node not found
    if (root == NULL)
        return -1;
    else
        return parent;
}
  
// Function to find the level of the given node
int LevelOfNode(struct Tree* root, int NodeData)
{
    // calculate the level of node
    int level = 0;
    while (root != NULL) {
  
        // if the node is found
        if (NodeData == root->data)
            break;
  
        // move to the left of the tree
        if (NodeData < root->data) {
            root = root->left;
        }
  
        // move to the right of the tree
        else {
            root = root->right;
        }
  
        // increase the level after every traversal
        level++;
    }
  
    // return the level of a given node
    return level;
}
  
// Driver Code
int main()
{
  
    // initialize the root as NULL
    struct Tree* root = NULL;
  
    // Inserts node in the tree
    // tree is the same as the one in image
    root = newNode(15);
    root->left = newNode(13);
    root->left->left = newNode(12);
    root->left->right = newNode(14);
    root->right = newNode(20);
    root->right->left = newNode(18);
    root->right->right = newNode(22);
  
    // Given Node
    int NodeData = 12;
    int p, level, sum;
  
    // function call to find the parent node
    p = ParentNode(root, NodeData);
  
    // if given Node is not present then print -1
    if (p == -1)
        cout << "-1\n";
  
    // if present then find the level of the node
    // and call the sum of cousin function
    else {
  
        // function call to find the level of that node
        level = LevelOfNode(root, NodeData);
  
        // sum of cousin nodes of the given nodes
        sum = SumOfCousin(root, p, 0, level);
  
        // print the sum
        cout << sum;
    }
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to find the sum of cousins
// of a node of a given BST
class GFG
{
  
// structure to store the binary tree
static class Tree 
{
    int data;
    Tree left, right;
};
  
// insertion of node in the binary tree
static Tree newNode(int data)
{
    // allocates memory
    Tree node = new Tree();
  
    // initializes data
    node.data = data;
  
    // marks the left and right
    // child as null
    node.left = node.right = null;
  
    // Return the node after allocating memory
    return (node);
}
  
// Function which calculates 
// the sum of the cousin Node
static int SumOfCousin(Tree root, int p,
                      int level1, int level)
{
    int sum = 0;
    if (root == null)
        return 0;
  
    // nodes which has same parent
    // as the given node will not be
    // taken to count for calculation
    if (p == root.data)
        return 0;
  
    // if the level is same
    // then it is a cousin
    // as parent checking has been
    // done above
    if (level1 == level)
        return root.data;
  
    // traverse in the tree left and right
    else
        sum += SumOfCousin(root.left, p, level1 + 1, level) + 
               SumOfCousin(root.right, p, level1 + 1, level);
  
    return sum;
}
  
// Function that returns the parent node
static int ParentNode(Tree root, int NodeData)
{
    int parent = -1;
  
    // traverse the full Binary tree
    while (root != null
    {
  
        // if node is found
        if (NodeData == root.data)
            break;
  
        // if less than move to left
        else if (NodeData < root.data) 
        {
            parent = root.data;
            root = root.left;
        }
  
        // if greater than move to rigth
        else 
        {
            parent = root.data;
            root = root.right;
        }
    }
  
    // Node not found
    if (root == null)
        return -1;
    else
        return parent;
}
  
// Function to find the level of the given node
static int LevelOfNode(Tree root, int NodeData)
{
    // calculate the level of node
    int level = 0;
    while (root != null
    {
  
        // if the node is found
        if (NodeData == root.data)
            break;
  
        // move to the left of the tree
        if (NodeData < root.data) 
        {
            root = root.left;
        }
  
        // move to the right of the tree
        else
        {
            root = root.right;
        }
  
        // increase the level after every traversal
        level++;
    }
  
    // return the level of a given node
    return level;
}
  
// Driver Code
public static void main(String[] args)
{
  
    // initialize the root as null
    Tree root = null;
  
    // Inserts node in the tree
    // tree is the same as the one in image
    root = newNode(15);
    root.left = newNode(13);
    root.left.left = newNode(12);
    root.left.right = newNode(14);
    root.right = newNode(20);
    root.right.left = newNode(18);
    root.right.right = newNode(22);
  
    // Given Node
    int NodeData = 12;
    int p, level, sum;
  
    // function call to find the parent node
    p = ParentNode(root, NodeData);
  
    // if given Node is not present then print -1
    if (p == -1)
        System.out.print("-1\n");
  
    // if present then find the level of the node
    // and call the sum of cousin function
    else
    {
  
        // function call to find the level of that node
        level = LevelOfNode(root, NodeData);
  
        // sum of cousin nodes of the given nodes
        sum = SumOfCousin(root, p, 0, level);
  
        // print the sum
        System.out.print(sum);
    }
}
}
  
// This code is contributed by 29AjayKumar

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to find the sum of cousins
// of a node of a given BST
using System;
  
class GFG
{
  
// structure to store the binary tree
class Tree 
{
    public int data;
    public Tree left, right;
};
  
// insertion of node in the binary tree
static Tree newNode(int data)
{
    // allocates memory
    Tree node = new Tree();
  
    // initializes data
    node.data = data;
  
    // marks the left and right
    // child as null
    node.left = node.right = null;
  
    // Return the node after allocating memory
    return (node);
}
  
// Function which calculates 
// the sum of the cousin Node
static int SumOfCousin(Tree root, int p,
                       int level1, int level)
{
    int sum = 0;
    if (root == null)
        return 0;
  
    // nodes which has same parent
    // as the given node will not be
    // taken to count for calculation
    if (p == root.data)
        return 0;
  
    // if the level is same
    // then it is a cousin
    // as parent checking has been
    // done above
    if (level1 == level)
        return root.data;
  
    // traverse in the tree left and right
    else
        sum += SumOfCousin(root.left, p, 
                           level1 + 1, level) + 
               SumOfCousin(root.right, p, 
                           level1 + 1, level);
  
    return sum;
}
  
// Function that returns the parent node
static int ParentNode(Tree root,
                      int NodeData)
{
    int parent = -1;
  
    // traverse the full Binary tree
    while (root != null
    {
  
        // if node is found
        if (NodeData == root.data)
            break;
  
        // if less than move to left
        else if (NodeData < root.data) 
        {
            parent = root.data;
            root = root.left;
        }
  
        // if greater than move to rigth
        else
        {
            parent = root.data;
            root = root.right;
        }
    }
  
    // Node not found
    if (root == null)
        return -1;
    else
        return parent;
}
  
// Function to find the level of the given node
static int LevelOfNode(Tree root, int NodeData)
{
    // calculate the level of node
    int level = 0;
    while (root != null
    {
  
        // if the node is found
        if (NodeData == root.data)
            break;
  
        // move to the left of the tree
        if (NodeData < root.data) 
        {
            root = root.left;
        }
  
        // move to the right of the tree
        else
        {
            root = root.right;
        }
  
        // increase the level
        // after every traversal
        level++;
    }
  
    // return the level of a given node
    return level;
}
  
// Driver Code
public static void Main(String[] args)
{
  
    // initialize the root as null
    Tree root = null;
  
    // Inserts node in the tree
    // tree is the same as the one in image
    root = newNode(15);
    root.left = newNode(13);
    root.left.left = newNode(12);
    root.left.right = newNode(14);
    root.right = newNode(20);
    root.right.left = newNode(18);
    root.right.right = newNode(22);
  
    // Given Node
    int NodeData = 12;
    int p, level, sum;
  
    // fuction call to find the parent node
    p = ParentNode(root, NodeData);
  
    // if given Node is not present
    // then print -1
    if (p == -1)
        Console.Write("-1\n");
  
    // if present then find the level of the node
    // and call the sum of cousin function
    else
    {
  
        // fuction call to find the level of that node
        level = LevelOfNode(root, NodeData);
  
        // sum of cousin nodes of the given nodes
        sum = SumOfCousin(root, p, 0, level);
  
        // print the sum
        Console.Write(sum);
    }
}
}
  
// This code is contributed by PrinciRaj1992

chevron_right


Output:

40

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.