Sum of all the parent nodes having child node x

30 Jun, 2021
Given a binary tree containing n nodes. The problem is to find the sum of all the parent node’s which have a child node with value x.Examples:  
Input : Binary tree with x = 2:
        4        
       / \       
      2   5      
     / \ / \     
    7  2 2  3    
Output : 11

        4        
       / \       
      2   5      
     / \ / \     
    7  2 2  3    

The highlighted nodes (4, 2, 5) above
are the nodes having 2 as a child node.
 
Algorithm:  
sumOfParentOfX(root,sum,x)
    if root == NULL
        return

    if (root->left && root->left->data == x) ||
       (root->right && root->right->data == x)
        sum += root->data
    
    sumOfParentOfX(root->left, sum, x)
    sumOfParentOfX(root->right, sum, x)
    
sumOfParentOfXUtil(root,x)
    Declare sum = 0
    sumOfParentOfX(root, sum, x)
    return sum
 
C++
Java
Python3
C#
Javascript
// C++ implementation to find the sum of all// the parent nodes having child node x#include <bits/stdc++.h> using namespace std; // Node of a binary treestruct Node{    int data;    Node *left, *right;}; // function to get a new nodeNode* getNode(int data){    // allocate memory for the node    Node *newNode =        (Node*)malloc(sizeof(Node));         // put in the data       newNode->data = data;    newNode->left = newNode->right = NULL;    return newNode;   } // function to find the sum of all the// parent nodes having child node xvoid sumOfParentOfX(Node* root, int& sum, int x){    // if root == NULL    if (!root)        return;         // if left or right child of root is 'x', then    // add the root's data to 'sum'    if ((root->left && root->left->data == x) ||        (root->right && root->right->data == x))        sum += root->data;         // recursively find the required parent nodes    // in the left and right subtree       sumOfParentOfX(root->left, sum, x);    sumOfParentOfX(root->right, sum, x);     } // utility function to find the sum of all// the parent nodes having child node xint sumOfParentOfXUtil(Node* root, int x){    int sum = 0;    sumOfParentOfX(root, sum, x);         // required sum of parent nodes    return sum;} // Driver program to test aboveint main(){    // binary tree formation    Node *root = getNode(4);           /*        4        */    root->left = getNode(2);           /*       / \       */    root->right = getNode(5);          /*      2   5      */    root->left->left = getNode(7);     /*     / \ / \     */    root->left->right = getNode(2);    /*    7  2 2  3    */    root->right->left = getNode(2);    root->right->right = getNode(3);         int x = 2;         cout << "Sum = "         << sumOfParentOfXUtil(root, x);              return 0;   }
// Java implementation to find// the sum of all the parent// nodes having child node xclass GFG{// sumstatic int sum = 0;          // Node of a binary treestatic class Node{    int data;    Node left, right;}; // function to get a new nodestatic Node getNode(int data){    // allocate memory for the node    Node newNode = new Node();         // put in the data        newNode.data = data;    newNode.left = newNode.right = null;    return newNode;    } // function to find the sum of all the// parent nodes having child node xstatic void sumOfParentOfX(Node root, int x){    // if root == NULL    if (root == null)        return;         // if left or right child    // of root is 'x', then    // add the root's data to 'sum'    if ((root.left != null && root.left.data == x) ||        (root.right != null && root.right.data == x))        sum += root.data;         // recursively find the required    // parent nodes in the left and    // right subtree        sumOfParentOfX(root.left, x);    sumOfParentOfX(root.right, x);     } // utility function to find the// sum of all the parent nodes// having child node xstatic int sumOfParentOfXUtil(Node root,                                 int x){    sum = 0;    sumOfParentOfX(root, x);         // required sum of parent nodes    return sum;} // Driver Codepublic static void main(String args[]){    // binary tree formation    Node root = getNode(4);         //     4        root.left = getNode(2);         //     / \        root.right = getNode(5);         //     2 5        root.left.left = getNode(7);     //     / \ / \        root.left.right = getNode(2); // 7 2 2 3    root.right.left = getNode(2);    root.right.right = getNode(3);         int x = 2;         System.out.println( "Sum = " +           sumOfParentOfXUtil(root, x));}} // This code is contributed by Arnab Kundu
# Python3 implementation to find the Sum of# all the parent nodes having child node x # function to get a new nodeclass getNode:    def __init__(self, data):                 # put in the data            self.data = data        self.left = self.right = None # function to find the Sum of all the# parent nodes having child node xdef SumOfParentOfX(root, Sum, x):         # if root == None    if (not root):        return         # if left or right child of root is 'x',    # then add the root's data to 'Sum'    if ((root.left and root.left.data == x) or        (root.right and root.right.data == x)):        Sum[0] += root.data         # recursively find the required parent    # nodes in the left and right subtree        SumOfParentOfX(root.left, Sum, x)    SumOfParentOfX(root.right, Sum, x) # utility function to find the Sum of all# the parent nodes having child node xdef SumOfParentOfXUtil(root, x):    Sum = [0]    SumOfParentOfX(root, Sum, x)         # required Sum of parent nodes    return Sum[0] # Driver Codeif __name__ == '__main__':         # binary tree formation    root = getNode(4)         #     4        root.left = getNode(2)         #     / \        root.right = getNode(5)         #     2 5        root.left.left = getNode(7)     #     / \ / \        root.left.right = getNode(2) # 7 2 2 3    root.right.left = getNode(2)    root.right.right = getNode(3)         x = 2         print("Sum = ", SumOfParentOfXUtil(root, x))     # This code is contributed by PranchalK
using System; // C# implementation to find// the sum of all the parent// nodes having child node xpublic class GFG{// sumpublic static int sum = 0;  // Node of a binary treepublic class Node{    public int data;    public Node left, right;} // function to get a new nodepublic static Node getNode(int data){    // allocate memory for the node    Node newNode = new Node();     // put in the data        newNode.data = data;    newNode.left = newNode.right = null;    return newNode;} // function to find the sum of all the// parent nodes having child node xpublic static void sumOfParentOfX(Node root, int x){    // if root == NULL    if (root == null)    {        return;    }     // if left or right child    // of root is 'x', then    // add the root's data to 'sum'    if ((root.left != null && root.left.data == x) ||       (root.right != null && root.right.data == x))    {        sum += root.data;    }     // recursively find the required    // parent nodes in the left and    // right subtree        sumOfParentOfX(root.left, x);    sumOfParentOfX(root.right, x); } // utility function to find the// sum of all the parent nodes// having child node xpublic static int sumOfParentOfXUtil(Node root, int x){    sum = 0;    sumOfParentOfX(root, x);     // required sum of parent nodes    return sum;} // Driver Codepublic static void Main(string[] args){    // binary tree formation    Node root = getNode(4); //     4    root.left = getNode(2); //     / \    root.right = getNode(5); //     2 5    root.left.left = getNode(7); //     / \ / \    root.left.right = getNode(2); // 7 2 2 3    root.right.left = getNode(2);    root.right.right = getNode(3);     int x = 2;     Console.WriteLine("Sum = " + sumOfParentOfXUtil(root, x));}} // This code is contributed by Shrikant13
<script>     // JavaScript implementation to find    // the sum of all the parent    // nodes having child node x         // sum    let sum = 0;         class Node    {        constructor(data) {           this.left = null;           this.right = null;           this.data = data;        }    }         // function to get a new node    function getNode(data)    {        // allocate memory for the node        let newNode = new Node(data);        return newNode;        }     // function to find the sum of all the    // parent nodes having child node x    function sumOfParentOfX(root, x)    {        // if root == NULL        if (root == null)            return;         // if left or right child        // of root is 'x', then        // add the root's data to 'sum'        if ((root.left != null && root.left.data == x) ||            (root.right != null && root.right.data == x))            sum += root.data;         // recursively find the required        // parent nodes in the left and        // right subtree            sumOfParentOfX(root.left, x);        sumOfParentOfX(root.right, x);     }     // utility function to find the    // sum of all the parent nodes    // having child node x    function sumOfParentOfXUtil(root, x)    {        sum = 0;        sumOfParentOfX(root, x);         // required sum of parent nodes        return sum;    }         // binary tree formation    let root = getNode(4);         //         4        root.left = getNode(2);         //       / \        root.right = getNode(5);         //      2 5        root.left.left = getNode(7);     //    / \ / \        root.left.right = getNode(2); //       7 2 2 3    root.right.left = getNode(2);    root.right.right = getNode(3);           let x = 2;           document.write( "Sum = " +           sumOfParentOfXUtil(root, x)); </script>
Output:  
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
Sum = 11
Time Complexity: O(n).  
Sum of all the parent nodes having child node x | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersSum of all the parent nodes having child node x | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:21•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=bG6nkyHkzXM" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
gardhiwasam
andrew1234
shrikanth13
PranchalKatiyar
rameshtravel07
Tree
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
AVL Tree | Set 1 (Insertion)
Introduction to Data Structures
What is Data Structure: Types, Classifications and Applications
A program to check if a binary tree is BST or not
Decision Tree
Top 50 Tree Coding Problems for Interviews
Segment Tree | Set 1 (Sum of given range)
Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash)
Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
Sorted Array to Balanced BST