Given a binary tree, the task is to find the sum of all the nodes whose parent is even.
Input: 1 / \ 3 8 / \ 5 6 / 1 Output: 11 The only even nodes are 8 and 6 and the sum of their children is 5 + 6 = 11. Input: 2 / \ 3 8 / / \ 2 5 6 / \ 1 3 Output: 25 3 + 8 + 5 + 6 + 3 = 25
Approach: Initialse sum = 0 and perform a recursive traversal of the tree and check if the node is even or not, if the node is even then add the values of its children to the sum. Finally, print the sum.
Below is the implementation of the above approach:
Time Complexity: O(n) where n is number of nodes in the given Binary Tree.
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.
- 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
- Sum of all the parent nodes having child node x
- Sum of all the child nodes with even grandparents in a Binary Tree
- Ways to color a skewed tree such that parent and child have different colors
- Count of nodes in a Binary Tree whose child is its prime factors
- Print the nodes having exactly one child in a Binary tree
- Print even positioned nodes of even levels in level order of the given binary tree
- Maximum parent children sum in Binary tree
- Check if all the Nodes in a Binary Tree having common values are at least D distance apart
- Print all even nodes of Binary Search Tree
- Find Height of Binary Tree represented by Parent array
- Construct Binary Tree from given Parent Array representation
- Lowest Common Ancestor in a Binary Tree | Set 2 (Using Parent Pointer)
- Find right sibling of a binary tree with parent pointers
- Construct Binary Tree from given Parent Array representation | Iterative Approach
- Find parent of given node in a Binary Tree with given postorder traversal
- Find the parent of a node in the given binary tree
- Difference between sum of even and odd valued nodes in a Binary Tree
- Create loops of even and odd values in a binary tree
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 Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.