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 a 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
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. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
In case you wish to attend live classes with industry experts, please refer Geeks Classes Live