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 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
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.
- Print all Coprime path of a Binary Tree
- Print Binary Tree levels in sorted order | Set 3 (Tree given as array)
- Print all K-sum levels in a Binary Tree
- Print all nodes between two given levels in Binary Tree
- Print all Exponential Levels of a Binary Tree
- Print all Palindromic Levels Of a Binary Tree
- Print Levels of all nodes in a Binary Tree
- Print all Prime Levels of a Binary Tree
- Print Binary Tree levels in sorted order | Set 2 (Using set)
- Print Binary Tree levels in sorted order
- Print even positioned nodes of even levels in level order of the given binary tree
- Print odd positioned nodes of even levels in level order of the given binary tree
- Print odd positioned nodes of odd levels in level order of the given binary tree
- Print even positioned nodes of odd levels in level order of the given binary tree
- Print updated levels of each node of a Complete Binary Tree based on difference in weights of subtrees
- Print the nodes at odd levels of a tree
- Sum of all the levels in a Binary Search Tree
- Averages of Levels in Binary Tree
- Left-Right traversal of all the levels of Binary tree
- Number of edges in a perfect binary tree with N levels
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.