Given a Binary Tree, the task is to print all Co-prime levels of this tree.
Any level of a Binary tree is said to be a Co-prime level, if all nodes of this level are co-prime to each other.
Input: 1 / \ 15 5 / / \ 11 4 15 \ / 2 3 Output: 1 11 4 15 2 3 Explanation: First, Third and Fourth levels are co-prime levels. Input: 7 / \ 21 14 / \ \ 77 16 3 / \ \ / 2 5 10 11 / 23 Output: 7 77 16 3 23 Explanation: First, Third and Fifth levels are co-prime levels.
Approach: In order to check if a level is Co-Prime level or not,
- First, we have to store all prime numbers using the Sieve of Eratosthenes.
- Then, we have to do level order traversal of the binary tree and have to save all elements of that level into a vector.
- This vector is used to store the levels of the tree while doing the level order traversal.
- Then for each level, check whether the elements have a GCD equal to 1 or not. If yes then this level is not Co-Prime, else print all elements of that level.
Below is the implementation of the above approach:
10 18 35 21 29 43 16 7