# Print all prime levels of a binary tree

In this problem, we are given a binary tree, and the task is to print all the levels of the tree that contain only prime numbers. A binary tree is a data structure in which each node can have at most two children, referred to as the left child and the right child.

## Example

Consider the following binary tree:

``````
10
/   \
2     3
/     / \
4     9   4
/  \    \    \
7    53   37   31
/  \     /
19   23   2

``````

The prime levels in the above binary tree are:

• Level 1: [10]
• Level 2: [2, 3]
• Level 4: [7, 53, 37, 31]
• Level 5: [19, 23]

## Idea to Solve the Problem

To solve this problem, we can perform a level order traversal of the binary tree using a custom queue data structure. For each level, we check if all the nodes on that level are prime numbers or not. If they are prime, we print the nodes; otherwise, we skip that level.

## Code Solution

``````// C program
// Print all prime levels of a binary tree
#include <stdio.h>

#include <stdlib.h>

//Node of binary tree
struct Node
{
int data;
struct Node *left, *right;
};
struct MyQueue
{
int level;
struct Node *element;
struct MyQueue *next;
};
//Create a binary tree nodes and node fields (data,pointer)
//And returning the reference of newly nodes
struct Node *insert(int data)
{
//create dynamic memory to new binary tree node
struct Node *new_node = (struct Node *) malloc(sizeof(struct Node));
if (new_node != NULL)
{
//Set node value
new_node->data = data;
new_node->left = NULL;
new_node->right = NULL;
}
else
{
printf("Memory Overflow\n");
}
//return reference
return new_node;
}
//Create a queue node and returns this node
struct MyQueue *enqueue(struct Node *tree_node)
{
//Make a new Queue node
struct MyQueue *new_node = (struct MyQueue *) malloc(sizeof(struct MyQueue));
if (new_node != NULL)
{
//Set node values
new_node->element = tree_node;
new_node->next = NULL;
}
else
{
printf("Memory Overflow\n");
}
return new_node;
}
//Remove a queue elements
void dequeue(struct MyQueue **front)
{
if ( *front != NULL)
{
struct MyQueue *remove = *front;
//Visit to next node
*front = remove->next;
remove->element = NULL;
remove->next = NULL;
//free node
free(remove);
remove = NULL;
}
}
//Check that whether given number is prime or not
int is_prime(int num)
{
if (num == 2 || num == 3 || num == 5)
{
return 1;
}
if (num <= 1 || (num % 2 == 0) || (num % 3 == 0) || (num % 5 == 0))
{
return 0;
}

int i = 11;

while ((i *i) <= num)
{
if (num % i == 0)
{
//When number is divisible of current i value
return 0;
}
else if (num % (i + 2) == 0)
{
//When number is divisible of current i + 2 value
return 0;
}
i = i + 6;
}
return 1;
}
//Detect and print prime level nodes
void prime_level(struct Node *root)
{
if (root != NULL)
{
//make a queue pointers
struct MyQueue *front = NULL, *tail = NULL;
struct MyQueue *temp = NULL;
//Get first node of tree
front = enqueue(root);
//Start level of first node is one
front->level = 1;
//Set tail node to first node
tail = front;
struct Node *node = root;
// Start to first node
temp = front;
//result node indicator
int status = 0;
int level = 0;
// Get nodes of all levels in a queue
while (temp != NULL)
{
//Tree node
node = temp->element;
level = temp->level;
if (node->left != NULL)
{
tail->next = enqueue(node->left);
tail->next->level = level + 1;
tail = tail->next;
}
if (node->right != NULL)
{
tail->next = enqueue(node->right);
tail->next->level = level + 1;
tail = tail->next;
}
//Visit to next node queue
temp = temp->next;
}
while (front != NULL)
{
temp = front;

//Reset the indicator value
status = 1;
level = front->level;

//Check that level node is prime or not
while (status == 1 && temp != NULL && temp->level == front->level)
{
status = is_prime(temp->element->data);
temp = temp->next;
}
temp = NULL;

if (status == 1)
{
printf(" [");
}
// When level nodes are prime,
// Then this loop are printed node value and remove level nodes
// Otherwise it's removing current level nodes
while (front != NULL && front->level == level)
{
if (status == 1)
{
//When all node is prime in a level
printf(" %d", front->element->data);
}
//remove  a queue node
dequeue( &front);
}
if (status == 1)
{
printf(" ]\n");
}
}
tail = NULL;
}
else
{
printf("Empty Tree\n");
}
}
int main()
{
struct Node *root = NULL;
/*
Construct Binary Tree
-----------------------
10
/   \
2     3
/     / \
4     9   5
/  \    \    \
7    53   37   31
/  \
19   23
-----------------------
*/
root = insert(10);
root->left = insert(2);
root->right = insert(3);
root->right->right = insert(5);
root->right->left = insert(9);
root->left->left = insert(4);
root->left->left->left = insert(7);
root->left->left->right = insert(53);
root->right->left->right = insert(37);
root->right->right->right = insert(31);
root->left->left->right->left = insert(19);
root->left->left->right->right = insert(23);
prime_level(root);
return 0;
}``````

#### Output

`````` [ 2 3 ]
[ 7 53 37 31 ]
[ 19 23 ]``````
``````/*
Java program
Print all prime levels of a binary tree
*/
//Binary Tree node
class TreeNode
{
public int data;
public TreeNode left;
public TreeNode right;
public TreeNode(int data)
{
//set node value
this.data = data;
this.left = null;
this.right = null;
}
}
// Queue Node
class QueueNode
{
public TreeNode element;
public QueueNode next;
public int level;
public QueueNode(TreeNode element, int level)
{
this.element = element;
this.next = null;
this.level = level;
}
}
//Define custom queue class
class MyQueue
{
public QueueNode front;
public QueueNode tail;
public MyQueue()
{
this.front = null;
this.tail = null;
}
//Add a new node at last of queue
public void enqueue(TreeNode element, int level)
{
QueueNode new_node = new QueueNode(element, level);
if (this.front == null)
{
//When first node of queue
this.front = new_node;
}
else
{
this.tail.next = new_node;
}
this.tail = new_node;
}
//Delete first node of queue
public void dequeue()
{
if (this.front != null)
{
if (this.tail == this.front)
{
this.tail = null;
this.front = null;
}
else
{
this.front = this.front.next;
}
}
}
public boolean is_empty()
{
if (this.front == null)
{
return true;
}
else
{
return false;
}
}
}
class BinaryTree
{
public TreeNode root;
public BinaryTree()
{
//set initial tree root to null
this.root = null;
}
//Check that whether given number is prime or not
public boolean is_prime(int num)
{
if (num == 2 || num == 3 || num == 5)
{
return true;
}
if (num <= 1 || (num % 2 == 0) || (num % 3 == 0) || (num % 5 == 0))
{
return false;
}
int i = 11;
while ((i * i) <= num)
{
if (num % i == 0)
{
//When number is divisible of current i value
return false;
}
else if (num % (i + 2) == 0)
{
//When number is divisible of current i + 2 value
return false;
}
i = i + 6;
}
return true;
}
//Determine whether given level contain all nodes are prime or not
public boolean is_all_prime(MyQueue queue, int level)
{
QueueNode temp = queue.front;
boolean status = true;
while (status == true && temp != null && temp.level == level)
{
status = is_prime(temp.element.data);
temp = temp.next;
}
return status;
}
// Display level which containing all prime nodes
public void prime_level()
{
if (this.root == null)
{
System.out.print("\n Empty Binary Tree \n");
}
else
{
//Get top node in tree
TreeNode node = this.root;
//Create a Queue
MyQueue queue = new MyQueue();
//Add first node at the level of one
queue.enqueue(node, 1);
QueueNode temp = queue.front;
int level = 0;
while (temp != null)
{
node = temp.element;
level = temp.level;
if (node.left != null)
{
queue.enqueue(node.left, level + 1);
}
if (node.right != null)
{
queue.enqueue(node.right, level + 1);
}
temp = temp.next;
}
boolean status = false;
level = 0;
while (queue.is_empty() == false)
{
level = queue.front.level;
status = is_all_prime(queue, level);
if (status == true)
{
System.out.print(" [");
}
// When level nodes are prime nodes,
// Then this loop are printed node value and remove level nodes
// Otherwise it's removing current level nodes
while (queue.is_empty() == false && queue.front.level == level)
{
if (status == true)
{
//When prime node exist
System.out.print(" " + queue.front.element.data);
}
//remove a queue node
queue.dequeue();
}
if (status == true)
{
System.out.print(" ]\n");
}
}
}
}
public static void main(String[] args)
{
//Object of Binary Tree
BinaryTree tree = new BinaryTree();
/*
Construct Binary Tree
-----------------------
10
/   \
2     3
/     / \
4     9   4
/  \    \    \
7    3    6   11
/  \     /
2    8   2
/ \
-1   9

-----------------------
*/
tree.root = new TreeNode(10);
tree.root.left = new TreeNode(2);
tree.root.right = new TreeNode(3);
tree.root.right.right = new TreeNode(5);
tree.root.right.left = new TreeNode(9);
tree.root.left.left = new TreeNode(4);
tree.root.left.left.left = new TreeNode(7);
tree.root.left.left.right = new TreeNode(53);
tree.root.right.left.right = new TreeNode(37);
tree.root.right.right.right = new TreeNode(31);
tree.root.left.left.right.left = new TreeNode(19);
tree.root.left.left.right.right = new TreeNode(23);
tree.prime_level();
}
}``````

#### Output

`````` [ 2 3 ]
[ 7 53 37 31 ]
[ 19 23 ]``````
``````//Include header file
#include <iostream>
using namespace std;

/*
C++ program
Print all prime levels of a binary tree
*/

//Binary Tree node
class TreeNode
{
public:
int data;
TreeNode *left;
TreeNode *right;
TreeNode(int data)
{
//set node value
this->data = data;
this->left = NULL;
this->right = NULL;
}
};
// Queue Node
class QueueNode
{
public: TreeNode *element;
QueueNode *next;
int level;
QueueNode(TreeNode *element, int level)
{
this->element = element;
this->next = NULL;
this->level = level;
}
};
//Define custom queue class
class MyQueue
{
public: QueueNode *front;
QueueNode *tail;
MyQueue()
{
this->front = NULL;
this->tail = NULL;
}
//Add a new node at last of queue
void enqueue(TreeNode *element, int level)
{
QueueNode *new_node = new QueueNode(element, level);
if (this->front == NULL)
{
//When first node of queue
this->front = new_node;
}
else
{
this->tail->next = new_node;
}
this->tail = new_node;
}
//Delete first node of queue
void dequeue()
{
if (this->front != NULL)
{
QueueNode *temp = this->front;
if (this->tail == this->front)
{
this->tail = NULL;
this->front = NULL;
}
else
{
this->front = this->front->next;
}
delete temp;
}
}
bool is_empty()
{
if (this->front == NULL)
{
return true;
}
else
{
return false;
}
}
};
class BinaryTree
{
public: TreeNode *root;
BinaryTree()
{
//set initial tree root to null
this->root = NULL;
}
//Check that whether given number is prime or not
bool is_prime(int num)
{
if (num == 2 || num == 3 || num == 5)
{
return true;
}
if (num <= 1 || (num % 2 == 0) || (num % 3 == 0) || (num % 5 == 0))
{
return false;
}
int i = 11;
while ((i *i) <= num)
{
if (num % i == 0)
{
//When number is divisible of current i value
return false;
}
else if (num % (i + 2) == 0)
{
//When number is divisible of current i + 2 value
return false;
}
i = i + 6;
}
return true;
}
//Determine whether given level contain all nodes are prime or not
bool is_all_prime(MyQueue queue, int level)
{
QueueNode *temp = queue.front;
bool status = true;
while (status == true && temp != NULL && temp->level == level)
{
status = this->is_prime(temp->element->data);
temp = temp->next;
}
return status;
}
// Display level which containing all prime nodes
void prime_level()
{
if (this->root == NULL)
{
cout << "\n Empty Binary Tree \n";
}
else
{
//Get top node in tree
TreeNode *node = this->root;
//Create a Queue
MyQueue queue = MyQueue();
//Add first node at the level of one
queue.enqueue(node, 1);
QueueNode *temp = queue.front;
int level = 0;
while (temp != NULL)
{
node = temp->element;
level = temp->level;
if (node->left != NULL)
{
queue.enqueue(node->left, level + 1);
}
if (node->right != NULL)
{
queue.enqueue(node->right, level + 1);
}
temp = temp->next;
}
bool status = false;
level = 0;
while (queue.is_empty() == false)
{
level = queue.front->level;
status = this->is_all_prime(queue, level);
if (status == true)
{
cout << " [";
}
// When level nodes are prime nodes,
// Then this loop are printed node value and remove level nodes
// Otherwise it's removing current level nodes
while (queue.is_empty() == false && queue.front->level == level)
{
if (status == true)
{
//When prime node exist
cout << " " << queue.front->element->data;
}
//remove a queue node
queue.dequeue();
}
if (status == true)
{
cout << " ]\n";
}
}
}
}
};
int main()
{
//Object of Binary Tree
BinaryTree tree = BinaryTree();
tree.root = new TreeNode(10);
tree.root->left = new TreeNode(2);
tree.root->right = new TreeNode(3);
tree.root->right->right = new TreeNode(5);
tree.root->right->left = new TreeNode(9);
tree.root->left->left = new TreeNode(4);
tree.root->left->left->left = new TreeNode(7);
tree.root->left->left->right = new TreeNode(53);
tree.root->right->left->right = new TreeNode(37);
tree.root->right->right->right = new TreeNode(31);
tree.root->left->left->right->left = new TreeNode(19);
tree.root->left->left->right->right = new TreeNode(23);
tree.prime_level();
return 0;
}``````

#### Output

`````` [ 2 3 ]
[ 7 53 37 31 ]
[ 19 23 ]``````
``````//Include namespace system
using System;

/*
C# program
Print all prime levels of a binary tree
*/

//Binary Tree node
class TreeNode
{
public int data;
public TreeNode left;
public TreeNode right;
public TreeNode(int data)
{
//set node value
this.data = data;
this.left = null;
this.right = null;
}
}
// Queue Node
class QueueNode
{
public TreeNode element;
public QueueNode next;
public int level;
public QueueNode(TreeNode element, int level)
{
this.element = element;
this.next = null;
this.level = level;
}
}
//Define custom queue class
class MyQueue
{
public QueueNode front;
public QueueNode tail;
public MyQueue()
{
this.front = null;
this.tail = null;
}
//Add a new node at last of queue
public void enqueue(TreeNode element, int level)
{
QueueNode new_node = new QueueNode(element, level);
if (this.front == null)
{
//When first node of queue
this.front = new_node;
}
else
{
this.tail.next = new_node;
}
this.tail = new_node;
}
//Delete first node of queue
public void dequeue()
{
if (this.front != null)
{
if (this.tail == this.front)
{
this.tail = null;
this.front = null;
}
else
{
this.front = this.front.next;
}
}
}
public Boolean is_empty()
{
if (this.front == null)
{
return true;
}
else
{
return false;
}
}
}
class BinaryTree
{
public TreeNode root;
public BinaryTree()
{
//set initial tree root to null
this.root = null;
}
//Check that whether given number is prime or not
public Boolean is_prime(int num)
{
if (num == 2 || num == 3 || num == 5)
{
return true;
}
if (num <= 1 || (num % 2 == 0) || (num % 3 == 0) || (num % 5 == 0))
{
return false;
}
int i = 11;
while ((i * i) <= num)
{
if (num % i == 0)
{
//When number is divisible of current i value
return false;
}
else if (num % (i + 2) == 0)
{
//When number is divisible of current i + 2 value
return false;
}
i = i + 6;
}
return true;
}
//Determine whether given level contain all nodes are prime or not
public Boolean is_all_prime(MyQueue queue, int level)
{
QueueNode temp = queue.front;
Boolean status = true;
while (status == true && temp != null && temp.level == level)
{
status = is_prime(temp.element.data);
temp = temp.next;
}
return status;
}
// Display level which containing all prime nodes
public void prime_level()
{
if (this.root == null)
{
Console.Write("\n Empty Binary Tree \n");
}
else
{
//Get top node in tree
TreeNode node = this.root;
//Create a Queue
MyQueue queue = new MyQueue();
//Add first node at the level of one
queue.enqueue(node, 1);
QueueNode temp = queue.front;
int level = 0;
while (temp != null)
{
node = temp.element;
level = temp.level;
if (node.left != null)
{
queue.enqueue(node.left, level + 1);
}
if (node.right != null)
{
queue.enqueue(node.right, level + 1);
}
temp = temp.next;
}
Boolean status = false;
level = 0;
while (queue.is_empty() == false)
{
level = queue.front.level;
status = is_all_prime(queue, level);
if (status == true)
{
Console.Write(" [");
}
// When level nodes are prime nodes,
// Then this loop are printed node value and remove level nodes
// Otherwise it's removing current level nodes
while (queue.is_empty() == false && queue.front.level == level)
{
if (status == true)
{
//When prime node exist
Console.Write(" " + queue.front.element.data);
}
//remove a queue node
queue.dequeue();
}
if (status == true)
{
Console.Write(" ]\n");
}
}
}
}
public static void Main(String[] args)
{
//Object of Binary Tree
BinaryTree tree = new BinaryTree();
tree.root = new TreeNode(10);
tree.root.left = new TreeNode(2);
tree.root.right = new TreeNode(3);
tree.root.right.right = new TreeNode(5);
tree.root.right.left = new TreeNode(9);
tree.root.left.left = new TreeNode(4);
tree.root.left.left.left = new TreeNode(7);
tree.root.left.left.right = new TreeNode(53);
tree.root.right.left.right = new TreeNode(37);
tree.root.right.right.right = new TreeNode(31);
tree.root.left.left.right.left = new TreeNode(19);
tree.root.left.left.right.right = new TreeNode(23);
tree.prime_level();
}
}``````

#### Output

`````` [ 2 3 ]
[ 7 53 37 31 ]
[ 19 23 ]``````
``````<?php
/*
Php program
Print all prime levels of a binary tree
*/

//Binary Tree node
class TreeNode
{
public \$data;
public \$left;
public \$right;

function __construct(\$data)
{
//set node value
\$this->data = \$data;
\$this->left = null;
\$this->right = null;
}
}
// Queue Node
class QueueNode
{
public \$element;
public \$next;
public \$level;

function __construct(\$element, \$level)
{
\$this->element = \$element;
\$this->next = null;
\$this->level = \$level;
}
}
//Define custom queue class
class MyQueue
{
public \$front;
public \$tail;

function __construct()
{
\$this->front = null;
\$this->tail = null;
}
//Add a new node at last of queue
public	function enqueue(\$element, \$level)
{
\$new_node = new QueueNode(\$element, \$level);
if (\$this->front == null)
{
//When first node of queue
\$this->front = \$new_node;
}
else
{
\$this->tail->next = \$new_node;
}
\$this->tail = \$new_node;
}
//Delete first node of queue
public	function dequeue()
{
if (\$this->front != null)
{
if (\$this->tail == \$this->front)
{
\$this->tail = null;
\$this->front = null;
}
else
{
\$this->front = \$this->front->next;
}
}
}
public	function is_empty()
{
if (\$this->front == null)
{
return true;
}
else
{
return false;
}
}
}
class BinaryTree
{
public \$root;

function __construct()
{
//set initial tree root to null
\$this->root = null;
}
//Check that whether given number is prime or not
public	function is_prime(\$num)
{
if (\$num == 2 || \$num == 3 || \$num == 5)
{
return true;
}
if (\$num <= 1 || (\$num % 2 == 0) || (\$num % 3 == 0) || (\$num % 5 == 0))
{
return false;
}
\$i = 11;
while ((\$i * \$i) <= \$num)
{
if (\$num % \$i == 0)
{
//When number is divisible of current i value
return false;
}
else if (\$num % (\$i + 2) == 0)
{
//When number is divisible of current i + 2 value
return false;
}
\$i = \$i + 6;
}
return true;
}
//Determine whether given level contain all nodes are prime or not
public	function is_all_prime(\$queue, \$level)
{
\$temp = \$queue->front;
\$status = true;
while (\$status == true && \$temp != null && \$temp->level == \$level)
{
\$status = \$this->is_prime(\$temp->element->data);
\$temp = \$temp->next;
}
return \$status;
}
// Display level which containing all prime nodes
public	function prime_level()
{
if (\$this->root == null)
{
echo "\n Empty Binary Tree \n";
}
else
{
//Get top node in tree
\$node = \$this->root;
//Create a Queue
\$queue = new MyQueue();
//Add first node at the level of one
\$queue->enqueue(\$node, 1);
\$temp = \$queue->front;
\$level = 0;
while (\$temp != null)
{
\$node = \$temp->element;
\$level = \$temp->level;
if (\$node->left != null)
{
\$queue->enqueue(\$node->left, \$level + 1);
}
if (\$node->right != null)
{
\$queue->enqueue(\$node->right, \$level + 1);
}
\$temp = \$temp->next;
}
\$status = false;
\$level = 0;
while (\$queue->is_empty() == false)
{
\$level = \$queue->front->level;
\$status = \$this->is_all_prime(\$queue, \$level);
if (\$status == true)
{
echo " [";
}
// When level nodes are prime nodes,
// Then this loop are printed node value and remove level nodes
// Otherwise it's removing current level nodes
while (\$queue->is_empty() == false && \$queue->front->level == \$level)
{
if (\$status == true)
{
//When prime node exist
echo " ". \$queue->front->element->data;
}
//remove a queue node
\$queue->dequeue();
}
if (\$status == true)
{
echo " ]\n";
}
}
}
}
}

function main()
{
//Object of Binary Tree
\$tree = new BinaryTree();
/*
Construct Binary Tree
-----------------------
10
/   \
2     3
/     / \
4     9   4
/  \    \    \
7    3    6   11
/  \     /
2    8   2
/ \
-1   9

-----------------------
*/
\$tree->root = new TreeNode(10);
\$tree->root->left = new TreeNode(2);
\$tree->root->right = new TreeNode(3);
\$tree->root->right->right = new TreeNode(5);
\$tree->root->right->left = new TreeNode(9);
\$tree->root->left->left = new TreeNode(4);
\$tree->root->left->left->left = new TreeNode(7);
\$tree->root->left->left->right = new TreeNode(53);
\$tree->root->right->left->right = new TreeNode(37);
\$tree->root->right->right->right = new TreeNode(31);
\$tree->root->left->left->right->left = new TreeNode(19);
\$tree->root->left->left->right->right = new TreeNode(23);
\$tree->prime_level();
}
main();``````

#### Output

`````` [ 2 3 ]
[ 7 53 37 31 ]
[ 19 23 ]``````
``````/*
Node Js program
Print all prime levels of a binary tree
*/
//Binary Tree node
class TreeNode
{
constructor(data)
{
//set node value
this.data = data;
this.left = null;
this.right = null;
}
}
// Queue Node
class QueueNode
{
constructor(element, level)
{
this.element = element;
this.next = null;
this.level = level;
}
}
//Define custom queue class
class MyQueue
{
constructor()
{
this.front = null;
this.tail = null;
}
//Add a new node at last of queue
enqueue(element, level)
{
var new_node = new QueueNode(element, level);
if (this.front == null)
{
//When first node of queue
this.front = new_node;
}
else
{
this.tail.next = new_node;
}
this.tail = new_node;
}
//Delete first node of queue
dequeue()
{
if (this.front != null)
{
if (this.tail == this.front)
{
this.tail = null;
this.front = null;
}
else
{
this.front = this.front.next;
}
}
}
is_empty()
{
if (this.front == null)
{
return true;
}
else
{
return false;
}
}
}
class BinaryTree
{
constructor()
{
//set initial tree root to null
this.root = null;
}
//Check that whether given number is prime or not
is_prime(num)
{
if (num == 2 || num == 3 || num == 5)
{
return true;
}
if (num <= 1 || (num % 2 == 0) || (num % 3 == 0) || (num % 5 == 0))
{
return false;
}
var i = 11;
while ((i * i) <= num)
{
if (num % i == 0)
{
//When number is divisible of current i value
return false;
}
else if (num % (i + 2) == 0)
{
//When number is divisible of current i + 2 value
return false;
}
i = i + 6;
}
return true;
}
//Determine whether given level contain all nodes are prime or not
is_all_prime(queue, level)
{
var temp = queue.front;
var status = true;
while (status == true && temp != null && temp.level == level)
{
status = this.is_prime(temp.element.data);
temp = temp.next;
}
return status;
}
// Display level which containing all prime nodes
prime_level()
{
if (this.root == null)
{
process.stdout.write("\n Empty Binary Tree \n");
}
else
{
//Get top node in tree
var node = this.root;
//Create a Queue
var queue = new MyQueue();
//Add first node at the level of one
queue.enqueue(node, 1);
var temp = queue.front;
var level = 0;
while (temp != null)
{
node = temp.element;
level = temp.level;
if (node.left != null)
{
queue.enqueue(node.left, level + 1);
}
if (node.right != null)
{
queue.enqueue(node.right, level + 1);
}
temp = temp.next;
}
var status = false;
level = 0;
while (queue.is_empty() == false)
{
level = queue.front.level;
status = this.is_all_prime(queue, level);
if (status == true)
{
process.stdout.write(" [");
}
// When level nodes are prime nodes,
// Then this loop are printed node value and remove level nodes
// Otherwise it's removing current level nodes
while (queue.is_empty() == false && queue.front.level == level)
{
if (status == true)
{
//When prime node exist
process.stdout.write(" " + queue.front.element.data);
}
//remove a queue node
queue.dequeue();
}
if (status == true)
{
process.stdout.write(" ]\n");
}
}
}
}
}

function main()
{
//Object of Binary Tree
var tree = new BinaryTree();
/*
Construct Binary Tree
-----------------------
10
/   \
2     3
/     / \
4     9   4
/  \    \    \
7    3    6   11
/  \     /
2    8   2
/ \
-1   9

-----------------------
*/
tree.root = new TreeNode(10);
tree.root.left = new TreeNode(2);
tree.root.right = new TreeNode(3);
tree.root.right.right = new TreeNode(5);
tree.root.right.left = new TreeNode(9);
tree.root.left.left = new TreeNode(4);
tree.root.left.left.left = new TreeNode(7);
tree.root.left.left.right = new TreeNode(53);
tree.root.right.left.right = new TreeNode(37);
tree.root.right.right.right = new TreeNode(31);
tree.root.left.left.right.left = new TreeNode(19);
tree.root.left.left.right.right = new TreeNode(23);
tree.prime_level();
}
main();``````

#### Output

`````` [ 2 3 ]
[ 7 53 37 31 ]
[ 19 23 ]``````
``````#   Python 3 program
#   Print all prime levels of a binary tree

# Binary Tree node
class TreeNode :

def __init__(self, data) :
# set node value
self.data = data
self.left = None
self.right = None

#  Queue Node
class QueueNode :

def __init__(self, element, level) :
self.element = element
self.next = None
self.level = level

# Define custom queue class
class MyQueue :

def __init__(self) :
self.front = None
self.tail = None

# Add a new node at last of queue
def enqueue(self, element, level) :
new_node = QueueNode(element, level)
if (self.front == None) :
# When first node of queue
self.front = new_node
else :
# Add node at last position
self.tail.next = new_node

self.tail = new_node

# Delete first node of queue
def dequeue(self) :
if (self.front != None) :
if (self.tail == self.front) :
self.tail = None
self.front = None
else :
self.front = self.front.next

def is_empty(self) :
if (self.front == None) :
return True
else :
return False

class BinaryTree :

def __init__(self) :
# set initial tree root to null
self.root = None

# Check that whether given number is prime or not
def is_prime(self, num) :
if (num == 2 or num == 3 or num == 5) :
return True

if (num <= 1 or(num % 2 == 0) or(num % 3 == 0) or(num % 5 == 0)) :
return False

i = 11
while ((i * i) <= num) :
if (num % i == 0) :
# When number is divisible of current i value
return False

elif(num % (i + 2) == 0) :
# When number is divisible of current i + 2 value
return False

i = i + 6

return True

# Determine whether given level contain all nodes are prime or not
def is_all_prime(self, queue, level) :
temp = queue.front
status = True
while (status == True and temp != None and temp.level == level) :
status = self.is_prime(temp.element.data)
temp = temp.next

return status

#  Display level which containing all prime nodes
def prime_level(self) :
if (self.root == None) :
print("\n Empty Binary Tree \n", end = "")
else :
# Get top node in tree
node = self.root
# Create a Queue
queue = MyQueue()
# Add first node at the level of one
queue.enqueue(node, 1)
temp = queue.front
level = 0
while (temp != None) :
node = temp.element
level = temp.level
if (node.left != None) :
queue.enqueue(node.left, level + 1)

if (node.right != None) :
queue.enqueue(node.right, level + 1)

temp = temp.next

status = False
level = 0
while (queue.is_empty() == False) :
level = queue.front.level
status = self.is_all_prime(queue, level)
if (status == True) :
print(" [", end = "")

#  When level nodes are prime nodes,
#  Then this loop are printed node value and remove level nodes
#  Otherwise it's removing current level nodes
while (queue.is_empty() == False and queue.front.level == level) :
if (status == True) :
# When prime node exist
print(" ", queue.front.element.data, end = "")

# remove a queue node
queue.dequeue()

if (status == True) :
print(" ]\n", end = "")

def main() :
# Object of Binary Tree
tree = BinaryTree()
#
# 		Construct Binary Tree
# 		-----------------------
# 		           10
# 		         /   \
# 		        2     3
# 		       /     / \
# 		      4     9   4
# 		     /  \    \    \
# 		    7    3    6   11
# 		        /  \     /
# 		       2    8   2
# 		           / \
# 		         -1   9
# 		-----------------------
#

tree.root = TreeNode(10)
tree.root.left = TreeNode(2)
tree.root.right = TreeNode(3)
tree.root.right.right = TreeNode(5)
tree.root.right.left = TreeNode(9)
tree.root.left.left = TreeNode(4)
tree.root.left.left.left = TreeNode(7)
tree.root.left.left.right = TreeNode(53)
tree.root.right.left.right = TreeNode(37)
tree.root.right.right.right = TreeNode(31)
tree.root.left.left.right.left = TreeNode(19)
tree.root.left.left.right.right = TreeNode(23)
tree.prime_level()

if __name__ == "__main__": main()``````

#### Output

`````` [  2  3 ]
[  7  53  37  31 ]
[  19  23 ]``````
``````#   Ruby program
#   Print all prime levels of a binary tree

# Binary Tree node
class TreeNode
# Define the accessor and reader of class TreeNode
attr_accessor :data, :left, :right

def initialize(data)
# set node value
self.data = data
self.left = nil
self.right = nil
end

end

#  Queue Node
class QueueNode
# Define the accessor and reader of class QueueNode
attr_accessor :element, :next, :level

def initialize(element, level)
self.element = element
self.next = nil
self.level = level
end

end

# Define custom queue class
class MyQueue
# Define the accessor and reader of class MyQueue
attr_accessor :front, :tail

def initialize()
self.front = nil
self.tail = nil
end

# Add a new node at last of queue
def enqueue(element, level)
new_node = QueueNode.new(element, level)
if (self.front == nil)
# When first node of queue
self.front = new_node
else
# Add node at last position
self.tail.next = new_node
end

self.tail = new_node
end

# Delete first node of queue
def dequeue()
if (self.front != nil)
if (self.tail == self.front)
self.tail = nil
self.front = nil
else
self.front = self.front.next
end

end

end

def is_empty()
if (self.front == nil)
return true
else
return false
end

end

end

class BinaryTree
# Define the accessor and reader of class BinaryTree
attr_accessor :root

def initialize()
# set initial tree root to null
self.root = nil
end

# Check that whether given number is prime or not
def is_prime(num)
if (num == 2 || num == 3 || num == 5)
return true
end

if (num <= 1 || (num % 2 == 0) || (num % 3 == 0) || (num % 5 == 0))
return false
end

i = 11
while ((i * i) <= num)
if (num % i == 0)
# When number is divisible of current i value
return false
elsif(num % (i + 2) == 0)
# When number is divisible of current i + 2 value
return false
end

i = i + 6
end

return true
end

# Determine whether given level contain all nodes are prime or not
def is_all_prime(queue, level)
temp = queue.front
status = true
while (status == true && temp != nil && temp.level == level)
status = self.is_prime(temp.element.data)
temp = temp.next
end

return status
end

#  Display level which containing all prime nodes
def prime_level()
if (self.root == nil)
print("\n Empty Binary Tree \n")
else
# Get top node in tree
node = self.root
# Create a Queue
queue = MyQueue.new()
# Add first node at the level of one
queue.enqueue(node, 1)
temp = queue.front
level = 0
while (temp != nil)
node = temp.element
level = temp.level
if (node.left != nil)
queue.enqueue(node.left, level + 1)
end

if (node.right != nil)
queue.enqueue(node.right, level + 1)
end

temp = temp.next
end

status = false
level = 0
while (queue.is_empty() == false)
level = queue.front.level
status = self.is_all_prime(queue, level)
if (status == true)
print(" [")
end

#  When level nodes are prime nodes,
#  Then this loop are printed node value and remove level nodes
#  Otherwise it's removing current level nodes
while (queue.is_empty() == false && queue.front.level == level)
if (status == true)
# When prime node exist
print(" ", queue.front.element.data)
end

# remove a queue node
queue.dequeue()
end

if (status == true)
print(" ]\n")
end

end

end

end

end

def main()
# Object of Binary Tree
tree = BinaryTree.new()
#
# 		Construct Binary Tree
# 		-----------------------
# 		           10
# 		         /   \
# 		        2     3
# 		       /     / \
# 		      4     9   4
# 		     /  \    \    \
# 		    7    3    6   11
# 		        /  \     /
# 		       2    8   2
# 		           / \
# 		         -1   9
# 		-----------------------
#

tree.root = TreeNode.new(10)
tree.root.left = TreeNode.new(2)
tree.root.right = TreeNode.new(3)
tree.root.right.right = TreeNode.new(5)
tree.root.right.left = TreeNode.new(9)
tree.root.left.left = TreeNode.new(4)
tree.root.left.left.left = TreeNode.new(7)
tree.root.left.left.right = TreeNode.new(53)
tree.root.right.left.right = TreeNode.new(37)
tree.root.right.right.right = TreeNode.new(31)
tree.root.left.left.right.left = TreeNode.new(19)
tree.root.left.left.right.right = TreeNode.new(23)
tree.prime_level()
end

main()``````

#### Output

`````` [ 2 3 ]
[ 7 53 37 31 ]
[ 19 23 ]
``````
``````/*
Scala program
Print all prime levels of a binary tree
*/

//Binary Tree node
class TreeNode(var data: Int,
var left: TreeNode,
var right: TreeNode)
{
def this(data: Int)
{
this(data, null, null);
}
}
// Queue Node
class QueueNode(var element: TreeNode,
var next: QueueNode,
var level: Int)
{
def this(element: TreeNode, level: Int)
{
this(element, null, level);
}
}
//Define custom queue class
class MyQueue(var front: QueueNode,
var tail: QueueNode)
{
def this()
{
this(null, null);
}
//Add a new node at last of queue
def enqueue(element: TreeNode, level: Int): Unit = {
var new_node: QueueNode = new QueueNode(element, level);
if (this.front == null)
{
//When first node of queue
this.front = new_node;
}
else
{
this.tail.next = new_node;
}
this.tail = new_node;
}
//Delete first node of queue
def dequeue(): Unit = {
if (this.front != null)
{
if (this.tail == this.front)
{
this.tail = null;
this.front = null;
}
else
{
this.front = this.front.next;
}
}
}
def is_empty(): Boolean = {
if (this.front == null)
{
return true;
}
else
{
return false;
}
}
}
class BinaryTree(var root: TreeNode)
{
def this()
{
this(null);
}
//Check that whether given number is prime or not
def is_prime(num: Int): Boolean = {
if (num == 2 || num == 3 || num == 5)
{
return true;
}
if (num <= 1 || (num % 2 == 0) || (num % 3 == 0) || (num % 5 == 0))
{
return false;
}
var i: Int = 11;
while ((i * i) <= num)
{
if (num % i == 0)
{
//When number is divisible of current i value
return false;
}
else if (num % (i + 2) == 0)
{
//When number is divisible of current i + 2 value
return false;
}
i = i + 6;
}
return true;
}
//Determine whether given level contain all nodes are prime or not
def is_all_prime(queue: MyQueue, level: Int): Boolean = {
var temp: QueueNode = queue.front;
var status: Boolean = true;
while (status == true && temp != null && temp.level == level)
{
status = is_prime(temp.element.data);
temp = temp.next;
}
return status;
}
// Display level which containing all prime nodes
def prime_level(): Unit = {
if (this.root == null)
{
print("\n Empty Binary Tree \n");
}
else
{
//Get top node in tree
var node: TreeNode = this.root;
//Create a Queue
var queue: MyQueue = new MyQueue();
//Add first node at the level of one
queue.enqueue(node, 1);
var temp: QueueNode = queue.front;
var level: Int = 0;
while (temp != null)
{
node = temp.element;
level = temp.level;
if (node.left != null)
{
queue.enqueue(node.left, level + 1);
}
if (node.right != null)
{
queue.enqueue(node.right, level + 1);
}
temp = temp.next;
}
var status: Boolean = false;
level = 0;
while (queue.is_empty() == false)
{
level = queue.front.level;
status = is_all_prime(queue, level);
if (status == true)
{
print(" [");
}
// When level nodes are prime nodes,
// Then this loop are printed node value and remove level nodes
// Otherwise it's removing current level nodes
while (queue.is_empty() == false && queue.front.level == level)
{
if (status == true)
{
//When prime node exist
print(" " + queue.front.element.data);
}
//remove a queue node
queue.dequeue();
}
if (status == true)
{
print(" ]\n");
}
}
}
}
}
object Main
{
def main(args: Array[String]): Unit = {
//Object of Binary Tree
var tree: BinaryTree = new BinaryTree();
/*
Construct Binary Tree
-----------------------
10
/   \
2     3
/     / \
4     9   4
/  \    \    \
7    3    6   11
/  \     /
2    8   2
/ \
-1   9

-----------------------
*/
tree.root = new TreeNode(10);
tree.root.left = new TreeNode(2);
tree.root.right = new TreeNode(3);
tree.root.right.right = new TreeNode(5);
tree.root.right.left = new TreeNode(9);
tree.root.left.left = new TreeNode(4);
tree.root.left.left.left = new TreeNode(7);
tree.root.left.left.right = new TreeNode(53);
tree.root.right.left.right = new TreeNode(37);
tree.root.right.right.right = new TreeNode(31);
tree.root.left.left.right.left = new TreeNode(19);
tree.root.left.left.right.right = new TreeNode(23);
tree.prime_level();
}
}``````

#### Output

`````` [ 2 3 ]
[ 7 53 37 31 ]
[ 19 23 ]``````
``````/*
Swift 4 program
Print all prime levels of a binary tree
*/
//Binary Tree node
class TreeNode
{
var data: Int;
var left: TreeNode? ;
var right: TreeNode? ;
init(_ data: Int)
{
//set node value
self.data = data;
self.left = nil;
self.right = nil;
}
}
// Queue Node
class QueueNode
{
var element: TreeNode? ;
var next: QueueNode? ;
var level: Int;
init(_ element: TreeNode? , _ level : Int)
{
self.element = element;
self.next = nil;
self.level = level;
}
}
//Define custom queue class
class MyQueue
{
var front: QueueNode? ;
var tail: QueueNode? ;
init()
{
self.front = nil;
self.tail = nil;
}
//Add a new node at last of queue
func enqueue(_ element: TreeNode? , _ level : Int)
{
let new_node: QueueNode? = QueueNode(element, level);
if (self.front == nil)
{
//When first node of queue
self.front = new_node;
}
else
{
self.tail!.next = new_node;
}
self.tail = new_node;
}
//Delete first node of queue
func dequeue()
{
if (self.front != nil)
{
if (self.tail === self.front)
{
self.tail = nil;
self.front = nil;
}
else
{
self.front = self.front!.next;
}
}
}
func is_empty() -> Bool
{
if (self.front == nil)
{
return true;
}
else
{
return false;
}
}
}
class BinaryTree
{
var root: TreeNode? ;
init()
{
//set initial tree root to null
self.root = nil;
}
//Check that whether given number is prime or not
func is_prime(_ num: Int) -> Bool
{
if (num == 2 || num == 3 || num == 5)
{
return true;
}
if (num <= 1 || (num % 2 == 0) || (num % 3 == 0) || (num % 5 == 0))
{
return false;
}
var i: Int = 11;
while ((i * i) <= num)
{
if (num % i == 0)
{
//When number is divisible of current i value
return false;
}
else if (num % (i + 2) == 0)
{
//When number is divisible of current i + 2 value
return false;
}
i = i + 6;
}
return true;
}
//Determine whether given level contain all nodes are prime or not
func is_all_prime(_ queue: MyQueue , _ level : Int) -> Bool
{
var temp: QueueNode? = queue.front;
var status: Bool = true;
while (status == true && temp != nil && temp!.level == level)
{
status = self.is_prime(temp!.element!.data);
temp = temp!.next;
}
return status;
}
// Display level which containing all prime nodes
func prime_level()
{
if (self.root == nil)
{
print("\n Empty Binary Tree \n", terminator: "");
}
else
{
//Get top node in tree
var node: TreeNode? = self.root;
//Create a Queue
let queue: MyQueue = MyQueue();
//Add first node at the level of one
queue.enqueue(node, 1);
var temp: QueueNode? = queue.front;
var level: Int = 0;
while (temp != nil)
{
node = temp!.element;
level = temp!.level;
if (node!.left != nil)
{
queue.enqueue(node!.left, level + 1);
}
if (node!.right != nil)
{
queue.enqueue(node!.right, level + 1);
}
temp = temp!.next;
}
var status: Bool = false;
level = 0;
while (queue.is_empty() == false)
{
level = queue.front!.level;
status = self.is_all_prime(queue, level);
if (status == true)
{
print(" [", terminator: "");
}
// When level nodes are prime nodes,
// Then this loop are printed node value and remove level nodes
// Otherwise it"s removing current level nodes
while (queue.is_empty() == false && queue.front!.level == level)
{
if (status == true)
{
//When prime node exist
print(" ", queue.front!.element!.data, terminator: "");
}
//remove a queue node
queue.dequeue();
}
if (status == true)
{
print(" ]\n", terminator: "");
}
}
}
}
}
func main()
{
//Object of Binary Tree
let tree: BinaryTree = BinaryTree();
tree.root = TreeNode(10);
tree.root!.left = TreeNode(2);
tree.root!.right = TreeNode(3);
tree.root!.right!.right = TreeNode(5);
tree.root!.right!.left = TreeNode(9);
tree.root!.left!.left = TreeNode(4);
tree.root!.left!.left!.left = TreeNode(7);
tree.root!.left!.left!.right = TreeNode(53);
tree.root!.right!.left!.right = TreeNode(37);
tree.root!.right!.right!.right = TreeNode(31);
tree.root!.left!.left!.right!.left = TreeNode(19);
tree.root!.left!.left!.right!.right = TreeNode(23);
tree.prime_level();
}
main();``````

#### Output

`````` [  2  3 ]
[  7  53  37  31 ]
[  19  23 ]``````

## Algorithm

1. Define the `TreeNode` class to represent a node in the binary tree. Each node will have a data value and pointers to its left and right children.
2. Define the `QueueNode` class to represent a node in the custom queue. Each node will contain a pointer to a binary tree node, its level, and a link to the next node in the queue.
3. Define the `MyQueue` class to implement the custom queue. It will have methods to enqueue and dequeue nodes, as well as a method to check if the queue is empty.
4. Define the `BinaryTree` class to represent the binary tree. It will have a method to check if a given number is prime or not (`is_prime`). Another method will determine whether all nodes at a given level are prime or not (`is_all_prime`). Finally, it will have the `prime_level` method to print all prime levels of the tree.
5. Perform a level order traversal of the binary tree using a queue. For each level, check if all the nodes are prime. If they are, print the nodes; otherwise, skip that level.

## Time Complexity

• The time complexity of checking whether a number is prime (`is_prime`) is O(sqrt(num)).
• The time complexity of performing a level order traversal of the binary tree to find prime levels is O(N), where N is the number of nodes in the tree.
• Therefore, the overall time complexity of the algorithm is O(N * sqrt(num)), where N is the number of nodes in the binary tree.

## Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.