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.
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.
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
Sum = 11
Time Complexity: O(n).
This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.
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.
- Sum of all the child nodes with even parent values in a Binary Tree
- Count all Grandparent-Parent-Child Triplets in a binary tree whose sum is greater than X
- Sum of all parent-child differences in a Binary Tree
- Ways to color a skewed tree such that parent and child have different colors
- Print the nodes having exactly one child in a Binary tree
- Sum of all the child nodes with even grandparents in a Binary Tree
- Count of nodes in a Binary Tree whose child is its prime factors
- Find parent of each node in a tree for multiple queries
- Find parent of given node in a Binary Tree with given postorder traversal
- Find the parent of a node in the given binary tree
- Sum of all odd nodes in the path connecting two given nodes
- Maximum parent children sum in Binary tree
- Node having maximum number of nodes less than its value in its subtree
- Change a Binary Tree so that every node stores sum of all nodes in left subtree
- Convert a Binary Tree such that every node stores the sum of all nodes in its right subtree
- Sum of the distances from every node to all other nodes is maximum
- Print all nodes in a binary tree having K leaves
- Check if all the Nodes in a Binary Tree having common values are at least D distance apart
- Count of all prime weight nodes between given nodes in the given Tree
- Find Height of Binary Tree represented by Parent array