VOOZH about

URL: https://www.geeksforgeeks.org/dsa/sum-parent-nodes-child-node-x/

⇱ Sum of all the parent nodes having child node x - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Sum of all the parent nodes having child node x

Last Updated : 16 Aug, 2022

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

Implementation:


Output
Sum = 11

Time Complexity: O(n). 

Auxiliary space: O(n) for call stack as it is using recursion

Comment
Article Tags:
Article Tags: