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 firstname.lastname@example.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.
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Sum of all the child nodes with even parent values in a Binary Tree
- Sum of all parent-child differences in a Binary Tree
- Ways to color a skewed tree such that parent and child have different colors
- Count all Grandparent-Parent-Child Triplets in a binary tree whose sum is greater than X
- Sum of all the child nodes with even grandparents in a Binary Tree
- Print the nodes having exactly one child in a Binary tree
- Count of nodes in a Binary Tree whose child is its prime factors
- Find the parent of a node in the given binary tree
- Find parent of each node in a tree for multiple queries
- Find parent of given node in a Binary Tree with given postorder traversal
- XOR of all the nodes in the sub-tree of the given node
- Print all nodes at distance k from a given node
- Sum of the distances from every node to all other nodes is maximum
- Check whether the given node is in the path between the nodes U and V
- Print the nodes that are just above the leaf node
- Check if two nodes are in same subtree of the root node
- Print all nodes that are at distance k from a leaf node
- Print all nodes at distance K from given node: Iterative Approach
- Number of leaf nodes in the subtree of every node of an n-ary tree
- Distance between two nodes of binary tree with node values from 1 to N