Print all Prime Levels of a Binary Tree
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
My Personal Notes arrow_drop_up
Please Login to comment...