Question:
Given a binary tree root node and 2 level, print the nodes between those levels.
Example:
Consider the image given below
If given level is 2 and 3 the nodes that should be printed are: 10, 25, 7, 15, 18, 30
Solution:
We do this with the help of level order traversal.
While doing level order traversal, we keep track of the level.
And if the level matches the given level, then we print the nodes.
Solution in C++
#include <iostream>
#include <queue>
#include <stack>
using namespace std;
// structure to hold binary tree node
struct Node
{
int data;
Node *left, *right;
Node(int data)
{
this->data = data;
this->left = this->right = nullptr;
}
};
void print_nodes_between_levels(Node* root, int start, int end)
{
queue<Node*> queue ;
queue.push(root);
Node *curr = NULL;
int level = 0;
while (!queue.empty())
{
level++;
int size = queue.size();
while (size != 0)
{
curr = queue.front();
queue.pop();
if (level >= start && level <= end)
{
cout << curr->data << " ";
}
if (curr->left != NULL)
{
queue.push(curr->left);
}
if (curr->right != NULL)
{
queue.push(curr->right);
}
size--;
}
if (level >= start && level <= end)
{
cout << ("\n");
};
}
}
int main()
{
Node* root = nullptr;
/* Binary tree:
16
/ \
/ \
10 25
/ \ / \
/ \ / \
7 15 18 30
*/
root = new Node(16);
root->left = new Node(10);
root->right = new Node(25);
root->left->left = new Node(7);
root->left->right = new Node(15);
root->right->left = new Node(18);
root->right->right = new Node(30);
print_nodes_between_levels(root, 2, 3);
return 0;
}
Output:
10 25
7 15 18 30