ในบทช่วยสอนนี้ เราจะพูดถึงโปรแกรมเพื่อพิมพ์โหนดระหว่างสองหมายเลขระดับที่กำหนดของไบนารีทรี
ในที่นี้ เราจะได้รับระดับต่ำและระดับสูงสำหรับไบนารีทรีเฉพาะ และเราต้องพิมพ์องค์ประกอบทั้งหมดระหว่างระดับที่กำหนด
เพื่อแก้ปัญหานี้ เราสามารถใช้การข้ามผ่านระดับตามคิว ในขณะที่เคลื่อนที่ผ่าน inorder traversal เราสามารถมีโหนดการทำเครื่องหมายที่ส่วนท้ายของแต่ละระดับ จากนั้นเราสามารถไปที่แต่ละระดับและพิมพ์โหนดได้หากโหนดการทำเครื่องหมายอยู่ระหว่างระดับที่กำหนด
ตัวอย่าง
#include <iostream>
#include <queue>
using namespace std;
struct Node{
int data;
struct Node* left, *right;
};
//to print the nodes between the levels
void print_nodes(Node* root, int low, int high){
queue <Node *> Q;
//creating the marking node
Node *marker = new Node;
int level = 1;
Q.push(root);
Q.push(marker);
while (Q.empty() == false){
Node *n = Q.front();
Q.pop();
//checking for the end of level
if (n == marker){
cout << endl;
level++;
if (Q.empty() == true || level > high)
break;
Q.push(marker);
continue;
}
if (level >= low)
cout << n->data << " ";
if (n->left != NULL) Q.push(n->left);
if (n->right != NULL) Q.push(n->right);
}
}
Node* create_node(int data){
Node* temp = new Node;
temp->data = data;
temp->left = temp->right = NULL;
return (temp);
}
int main(){
struct Node *root= create_node(20);
root->left= create_node(8);
root->right= create_node(22);
root->left->left= create_node(4);
root->left->right= create_node(12);
root->left->right->left= create_node(10);
root->left->right->right= create_node(14);
cout << "Elements between the given levels are :";
print_nodes(root, 2, 3);
return 0;
} ผลลัพธ์
Elements between the given levels are : 8 22 4 12