Input: 1 / \ 15 20 / \ / \ 3 5 4 2 \ / 2 3 Output: 3 Explanation: Children of 15 (3, 5) are prime factors of 15 Child of 20 (2) is prime factors of 20 Child of 4 (2) is prime factors of 4 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 if children exist or not.
- If 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 of Eratosthenes to precompute the prime numbers to do the checking in O(1).
Below is the implementation of the above approach:
- Time Complexity : O(N).
In dfs, every node of the tree is processed once and hence the complexity due to the bfs is O(N) if there are total N nodes in the tree. Also, for processing each node the SieveOfEratosthenes() function is used which has a complexity of O(sqrt(N)) too but since this function is executed only once, it does not affect the overall time complexity. Therefore, the time complexity is O(N).
- Auxiliary Space : O(N).
Extra space is used for the prime array, so the space complexity is O(N).
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.