Computer >> Máy Tính >  >> Lập trình >> C ++

In theo thứ tự mức in từng dòng trong Lập trình C ++.

Với cây nhị phân, hàm phải tìm ra thứ tự cấp của từng dòng một.

Duyệt theo thứ tự mức độ:Left Root Right, có nghĩa là đầu tiên in con bên trái của một nút hơn giá trị của một gốc và sau đó chuyển đến con bên phải nhưng ở đây chúng ta phải thực hiện từng dòng một sẽ bắt đầu từ bên trái và sẽ kết thúc ở bên phải nút của một cây nhị phân nhất định.

In theo thứ tự mức in từng dòng trong Lập trình C ++.

Cây nhị phân được đưa ra ở trên sẽ tạo ra kết quả sau -

Level 0: 3
Level 1: 2 1
Level 2: 10 20 30

Thuật toán

START
Step 1 -> create a structure of a node as
   struct node
      struct node *left, *right
      int data
   End
Step 2 -> function to create a node
   node* newnode(int data)
   node *temp = new node
   temp->data = data
   temp->left = temp->right= NULL
   return temp
step 3 -> function for inorder traversal
   void levelorder(node *root)
   IF root = NULL
      Return
   End
   queue<node *> que
   que.push(root)
   Loop While que.empty() = false
      int count = que.size()
      Loop While count > 0
         node *node = que.front()
         print node->data
         que.pop()
      IF node->left != NULL
         que.push(node->left)
      End
      IF node->right != NULL
         que.push(node->right)
      End
      Decrement count by 1
   End
End
Step 4 -> In main() function
   Create tree using node *root = newnode(3)
   Call levelorder(root)
STOP

Ví dụ

#include <iostream>
#include <queue>
using namespace std;
//it will create a node structure
struct node{
   struct node *left;
   int data;
   struct node *right;
};
void levelorder(node *root){
   if (root == NULL)
      return;
   queue<node *> que;
   que.push(root);
   while (que.empty() == false){
      int count = que.size();
      while (count > 0){
         node *node = que.front();
         cout << node->data << " ";
         que.pop();
         if (node->left != NULL)
            que.push(node->left);
         if (node->right != NULL)
            que.push(node->right);
         count--;
      }
   }
}
//it will create a new node
node* newnode(int data){
   node *temp = new node;
   temp->data = data;
   temp->left = NULL;
   temp->right = NULL;
   return temp;
}
int main(){
   // it will generate the binary tree
   node *root = newnode(3);
   root->left = newnode(2);
   root->right = newnode(1);
   root->left->left = newnode(10);
   root->left->right = newnode(20);
   root->right->right = newnode(30);
   levelorder(root);
   return 0;
}

Đầu ra

nếu chúng ta chạy chương trình trên thì nó sẽ tạo ra kết quả sau

3 2 1 10 20 30