Print all Prime Levels of a Binary Tree


In this problem, we will print all prime levels of the given binary tree.

We will use the level order traversal technique to traverse each binary tree level and check whether all nodes contain the prime integer for the particular level.

Problem statement − We have given a binary tree and need to print all prime levels of the binary tree. It is given that if all nodes of any binary tree contain a prime integer, we can say a particular level is a prime level.

Sample examples

Input 

                 23
               /     \ 
            12       13 
           /  \        \
        17    19      23 
       / \      \      / 
     3    7     19    11    

Output

23
17  19  23
3  7  19  11

Explanation − We have printed all prime levels of the given binary tree.

Input 

                  5
               /     \ 
              7       2 
             /  \     / \
            3    5   74 76 
           /  \         
          23  1 7       

Output

5
7  2
23  17

Explanation − The first, second, and fourth levels are prime levels.

Approach 1

In this approach, we will traverse through each level. After that, we will check whether all numbers of the particular level are prime. If yes, we print the level.

Algorithm

Step 1− Define the structure of the tree.

Step 2− Define the createNewNode() function to create a new node with a given value.

Step 3− Create a binary tree.

Step 4− Execute the getSize() function to get the number of levels into the tree.

Step 4.1− In the getSize() function, If the head node is NULL, return 0.

Step 4.2− Else, make a recursive call for the left nodes and right nodes, and add 1 to its resultant value.

Step 5− Create a queue of length equal to tree size and insert the head node into the queue.

Step 6− Execute the getPrimeLevels() function to print prime levels.

Step 6.1− In the getPrimeLevels() function, execute the checkForPrime() function to check if the root element is a prime.

Step 6.1.1− In the checkForPrime() function, if the number is 1, return false.

Step 6.1.2− Make iterations using the for loop until p*p < = num. In the loop, if num is divisible by p, return false.

Step 6.1.3− Return false in the last.

Step 6.2− Now, use the while loop to traverse each level.

Step 6.3− Use the nested while loop to travese the particular level.

Step 6.3.1− In the nested loop, take the first node from the queue.

Step 6.3.2− If the current node's left child exists, insert it into the queue.

Step 6.3.3− If the right node of the current node exists, insert it into the queue.

Step 6.3.4− Increment the ‘ind’ value by 1.

Step 6.4− Execute the checkForPrimeLevel() function to check whether the current level is prime.

Step 6.4.1− In the checkForPrimeLKevel() function, we check whether each number is prime. If yes, we return true. Otherwise, we return false.

Step 6.5− If checkForPrimeLevel() function returns true, we execute the showLevel() function to show the current level. In which, we travese the queue containing the nodes of the current level and print its value.

Example

#include <bits/stdc++.h>
using namespace std;
// Tree structure
struct TreeNode {
    int val;
    struct TreeNode *left, *right;
};
// Function for creating a new node
TreeNode *createNewNode(int val) {
    TreeNode *tmp = new TreeNode;
    tmp->val = val;
    tmp->left = NULL;
    tmp->right = NULL;
    return (tmp);
}
// Check if a number is Prime or not
bool checkForPrime(int num) {
    if (num == 1)
        return false;
    for (int p = 2; p * p <= num; p++) {
        if (num % p == 0) {
            return false;
        }
    }
    return true;
}
// Print the particular level of a given
void showLevel(struct TreeNode *que[], int ind, int sz) {
    // Traverse the queue and print all values
    for (int p = ind; p < sz; p++) {
        cout << que[p]->val << " ";
    }
    cout << endl;
}
// Check if a particular level is Prime
bool checkForPrimeLevel(struct TreeNode *que[], int ind, int sz) {
    for (int p = ind; p < sz; p++) {
        if (!checkForPrime(que[ind++]->val)) {
            return false;
        }
    }
    // When all node values are Prime
    return true;
}
void getPrimeLevels(struct TreeNode *head, struct TreeNode *que[], int ind, int sz) {
    // Print head node
    if (checkForPrime(que[ind]->val)) {
        cout << que[ind]->val << endl;
    }
    while (ind < sz) { 
        int temp_size = sz;
        while (ind < temp_size) {
            struct TreeNode *temp = que[ind];
            // Insert left child to queue
            if (temp->left != NULL)
                que[sz++] = temp->left;
            // Insert right child to queue
            if (temp->right != NULL)
                que[sz++] = temp->right;
            ind++;
        }
        // Check for prime level
        if (checkForPrimeLevel(que, ind, sz - 1)) {
            showLevel(que, ind, sz);
        }
    }
}
// Get the size of the tree
int getSize(struct TreeNode *head) {
    // Base condition
    if (head == NULL)
        return 0;
    return 1 + getSize(head->left) + getSize(head->right);
}
void ShowAllPrimeLevels(struct TreeNode *head) {
    int treeSize = getSize(head);
    struct TreeNode *queue[treeSize];
    // Insert head node in queue
    queue[0] = head;
    // FInd prime levels
    getPrimeLevels(head, queue, 0, 1);
}
int main() {
    TreeNode *head = createNewNode(5);
    head->left = createNewNode(7);
    head->right = createNewNode(2);
    head->left->left = createNewNode(3);
    head->left->right = createNewNode(5);
    head->right->left = createNewNode(76);
    head->right->right = createNewNode(54);
    head->left->left->left = createNewNode(23);
    head->left->left->right = createNewNode(17);
    ShowAllPrimeLevels(head);
    return 0;
}

Output

5
7 2 
23 17 

Time complexity − O(n * sqrt(max_val)), where O(n) is to traverse the binary tree, and O(sqrt(max_val)) is to check whether the number is a prime number or not.

Space complexity − O(M), where M is the maximum number of nodes in the particular level.

Here, we have printed all prime levels using the level order traversal. Programmers can print the non−prime levels. In which they can print the level if all node of the particular level contains the non−prime number.

Updated on: 22-Jul-2023

52 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements