Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to print nodes between two given level numbers of a binary tree using C++
In this tutorial, we will be discussing a program to print nodes between the two given level numbers of a binary tree.
In this, we will be given a low level and a high level for a particular binary tree and we have to print all the elements between the given levels.
To solve this we can use queue-based level traversal. While moving through inorder traversal we can have a marking node at the end of each level. Then we can go to each level and print its nodes if the marking node exists between the given levels.
Example
#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;
}
Output
Elements between the given levels are : 8 22 4 12
Advertisements