Given a Binary Tree, the task is to print the count of nodes having both children and both of them are its prime factors.
Input: 1 / \ 15 20 / \ / \ 3 5 4 2 \ / 2 3 Output: 1 Explanation: Children of 15 (3, 5) are prime factors of 15 Input: 7 / \ 210 14 / \ \ 70 14 30 / \ / \ 2 5 3 5 / 23 Output: 2 Explanation: Children of 70 (2, 5) are prime factors of 70 Children of 30 (3, 5) are prime factors of 30
- Traverse the given Binary Tree and for each node, check both the children exists or not.
- If both the children exist, check if each child is a prime factor of this node or not.
- Keep the count of such nodes and print it at the end.
- In order to check if a factor is prime, we will use Sieve to precompute the prime numbers to do the checking in O(1).
Below is the implementation of the above approach.
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.