Given a Binary Tree, calculate the sum of nodes with even valued Grandparents.
Input: 22 / \ 3 8 / \ / \ 4 8 1 9 \ 2 Output: 24 Explanation The nodes 4, 8, 2, 1, 9 has even value grandparents. Hence sum = 4 + 8 + 1 + 9 + 2 = 24. Input: 1 / \ 2 3 / \ / \ 4 5 6 7 / 8 Output: 8 Explanation Only 8 has 2 as a grandparent.
Approach: To solve the problem mentioned above, for each node that is not null, check if they have a grandparent and if their grandparent is even valued add the node’s data to the sum.
Below is the implementation of the above approach:
Time Complexity: O(N)
Space Complexity: O(H), Used by recursion stack where H = height of the 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.
- Sum of all the child nodes with even parent values in a Binary Tree
- 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
- 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
- Print all even nodes of Binary Search Tree
- Difference between sum of even and odd valued nodes in a Binary Tree
- Count the nodes of the tree which make a pangram when concatenated with the sub-tree nodes
- Difference between sums of odd level and even level nodes of a Binary Tree
- Difference between sums of odd position and even position nodes for each level of a Binary Tree
- Print even positioned nodes of odd levels in level order of the given binary tree
- Print odd positioned nodes of even levels in level order of the given binary tree
- Sink even nodes in Binary Tree
- Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
- Change a Binary Tree so that every node stores sum of all nodes in left subtree
- Sum of all nodes in a binary tree
- Sum of all leaf nodes of binary tree
- Sum of heights of all individual nodes 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.