Given a Binary Tree, the task is to print all prime levels of this tree.
Any level of a Binary tree is said to be a prime level, if all nodes of this level are prime.
Input: 1 / \ 15 13 / / \ 11 7 29 \ / 2 3 Output: 11 7 29 2 3 Explanation: Third and Fourth levels are prime levels. Input: 7 / \ 23 41 / \ \ 31 16 3 / \ \ / 2 5 17 11 / 23 Output: 7 23 41 2 5 17 11 23 Explanation: First, Second, Fourth and Fifth levels are prime levels.
Approach: In order to check if a level is Prime level or not,
- we first need to make level order traversal of the binary tree to get the node values of each level.
- Here a Queue data structure is used to store the levels of the tree while doing the level order traversal.
- Then for each level, check if it is a prime level or not.
Below is the implementation of the above approach:
13 11 19 23 7
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Print all Co-Prime Levels 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 Palindromic Levels Of a Binary Tree
- Print all nodes between two given levels in Binary Tree
- Print all Exponential Levels of a Binary Tree
- Print Levels of all nodes in a Binary Tree
- Print Binary Tree levels in sorted order
- Print Binary Tree levels in sorted order | Set 2 (Using set)
- Print even positioned nodes of even 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 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 updated levels of each node of a Complete Binary Tree based on difference in weights of subtrees
- Print the nodes of the Binary Tree whose height is a Prime number
- Print the nodes at odd levels of a tree
- Averages of Levels in Binary Tree
- Left-Right traversal of all the levels of Binary tree
- Maximum sum of non-leaf nodes among all levels of the given binary tree
- Maximum sum of leaf nodes among all levels of the given 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.