📜  打印二叉树的所有素数

📅  最后修改于: 2021-04-29 06:14:00             🧑  作者: Mango

给定一个二叉树,任务是打印该树的所有主要级别。

例子:

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.

方法:为了检查某个级别是否为主要级别,

  • 首先,我们需要对二叉树进行级别顺序遍历,以获得每个级别的节点值。
  • 这里,队列数据结构用于在执行级别顺序遍历时存储树的级别。
  • 然后,对于每个级别,检查它是否是主要级别。

下面是上述方法的实现:

C++
// C++ program for printing a prime
// levels of binary Tree
 
#include 
using namespace std;
 
// A Tree node
struct Node {
    int key;
    struct Node *left, *right;
};
 
// Utility function to create a new node
Node* newNode(int key)
{
    Node* temp = new Node;
    temp->key = key;
    temp->left = temp->right = NULL;
    return (temp);
}
 
// Function to check whether node
// Value is prime or not
bool isPrime(int n)
{
    if (n == 1)
        return false;
 
    // Iterate from 2 to sqrt(n)
    for (int i = 2; i * i <= n; i++) {
 
        // If it has a factor
        if (n % i == 0) {
            return false;
        }
    }
 
    return true;
}
 
// Function to print a Prime level
void printLevel(struct Node* queue[],
                int index, int size)
{
    for (int i = index; i < size; i++) {
        cout << queue[i]->key << " ";
    }
 
    cout << endl;
}
 
// Function to check whether given level is
// prime level or not
bool isLevelPrime(struct Node* queue[],
                  int index, int size)
{
    for (int i = index; i < size; i++) {
        // Check value of node is
        // pPrime or not
        if (!isPrime(queue[index++]->key)) {
            return false;
        }
    }
 
    // Return true if for loop
    // iIterate completely
    return true;
}
 
// Utility function to get Prime
// Level of a given Binary tree
void findPrimeLevels(struct Node* node,
                     struct Node* queue[],
                     int index, int size)
{
    // Print root node value, if Prime
    if (isPrime(queue[index]->key)) {
        cout << queue[index]->key << endl;
    }
 
    // Run while loop
    while (index < size) {
        int curr_size = size;
 
        // Run inner while loop
        while (index < curr_size) {
            struct Node* temp = queue[index];
 
            // Push left child in a queue
            if (temp->left != NULL)
                queue[size++] = temp->left;
 
            // Push right child in a queue
            if (temp->right != NULL)
                queue[size++] = temp->right;
 
            // Increament index
            index++;
        }
 
        // If condition to check, level is
        // prime or not
        if (isLevelPrime(
                queue, index, size - 1)) {
 
            // Function call to print
            // prime level
            printLevel(queue, index, size);
        }
    }
}
 
// Function to find total no of nodes
// In a given binary tree
int findSize(struct Node* node)
{
    // Base condition
    if (node == NULL)
        return 0;
 
    return 1
           + findSize(node->left)
           + findSize(node->right);
}
 
// Function to find Prime levels
// In a given binary tree
void printPrimeLevels(struct Node* node)
{
    int t_size = findSize(node);
 
    // Create queue
    struct Node* queue[t_size];
 
    // Push root node in a queue
    queue[0] = node;
 
    // Function call
    findPrimeLevels(node, queue, 0, 1);
}
 
// Driver Code
int main()
{
    /*      10
         /    \
        13     11
            /  \
           19    23
          / \    / \
         21 29 43 15
                  /
                 7 */
 
    // Create Binary Tree as shown
 
    Node* root = newNode(10);
    root->left = newNode(13);
    root->right = newNode(11);
 
    root->right->left = newNode(19);
    root->right->right = newNode(23);
 
    root->right->left->left = newNode(21);
    root->right->left->right = newNode(29);
    root->right->right->left = newNode(43);
    root->right->right->right = newNode(15);
    root->right->right->right->left = newNode(7);
 
    // Print Prime Levels
    printPrimeLevels(root);
 
    return 0;
}


Python3
# Python3 program for printing a prime
# levels of binary Tree
  
# A Tree node
class Node:
     
    def __init__(self, key):
       
        self.key = key
        self.left = None
        self.right = None
                 
# function to create a
# new node
def newNode(key):
 
    temp = Node(key);   
    return temp;
  
# Function to check whether
# node Value is prime or not
def isPrime(n):
 
    if (n == 1):
        return False;   
    i = 2
     
    # Iterate from 2
    # to sqrt(n)
    while(i * i <= n):
  
        # If it has a factor
        if (n % i == 0):
            return False;
        i += 1
  
    return True;
 
# Function to print a
# Prime level
def printLevel(queue,
               index, size):
     
    for i in range(index, size):
        print(queue[i].key, end = ' ')
    print()
  
  
# Function to check whether
# given level is prime level
# or not
def isLevelPrime(queue,
                 index, size):
     
    for i in range(index, size):
     
        # Check value of node is
        # pPrime or not
        if (not isPrime(queue[index].key)):
            index += 1
            return False;       
  
    # Return true if for loop
    # iIterate completely
    return True;
  
# Utility function to get Prime
# Level of a given Binary tree
def findPrimeLevels(node, queue,
                    index, size):
 
    # Print root node value, if Prime
    if (isPrime(queue[index].key)):
        print(queue[index].key)
  
    # Run while loop
    while (index < size):
        curr_size = size;
  
        # Run inner while loop
        while (index < curr_size):
            temp = queue[index];
  
            # Push left child in a queue
            if (temp.left != None):
                queue[size] = temp.left;
                size+=1
  
            # Push right child in a queue
            if (temp.right != None):
                queue[size] = temp.right;
                size+=1
  
            # Increament index
            index+=1;
         
  
        # If condition to check, level
        # is prime or not
        if (isLevelPrime(queue, index,
                         size - 1)):
  
            # Function call to print
            # prime level
            printLevel(queue,
                       index, size);       
  
# Function to find total no
# of nodes In a given binary
# tree
def findSize(node):
 
    # Base condition
    if (node == None):
        return 0;
  
    return (1 + findSize(node.left) +
                findSize(node.right));
  
# Function to find Prime levels
# In a given binary tree
def printPrimeLevels(node):
 
    t_size = findSize(node);
  
    # Create queue
    queue=[0 for i in range(t_size)]
  
    # Push root node in a queue
    queue[0] = node;
  
    # Function call
    findPrimeLevels(node, queue,
                    0, 1);
     
# Driver code    
if __name__ == "__main__":
     
    '''      10
         /    \
        13     11
            /  \
           19    23
          / \    / \
         21 29 43 15
                  /
                 7 '''
  
    # Create Binary Tree as shown
    root = newNode(10);
    root.left = newNode(13);
    root.right = newNode(11);
  
    root.right.left = newNode(19);
    root.right.right = newNode(23);
  
    root.right.left.left = newNode(21);
    root.right.left.right = newNode(29);
    root.right.right.left = newNode(43);
    root.right.right.right = newNode(15);
    root.right.right.right.left = newNode(7);
  
    # Print Prime Levels
    printPrimeLevels(root);
 
# This code is contributed by Rutvik_56


输出:
13 11 
19 23 
7