使用 C++ 打印二叉树中两个给定级别节点的程序
在本教程中,将探讨打印二叉树两个给定级别节点的程序。
在这里,将为特定二叉树设定低级别和高级别,并且我们必须打印给定级别之间的所有元素。
要解决此问题,可以使用基于队列的级别遍历。在中序遍历中移动时,可以在每个级别的末尾设置一个标记节点。然后,我们可以进入每个级别并打印其节点,如果标记节点存在于给定级别之间,就可以打印其节点。
示例
#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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP