Question:
Given a binary tree root node and a level, display all the nodes present in that level.
Example:
Consider the image given below:
Form the image above,
Nodes at level 1 are : 16
Nodes at level 2 are : 10, 25
Nodes at level 3 are : 7, 15, 18, 30
Solution:
This problem can be solved by recursive traversal, by using below logic:
if(level == 1) { print(node->data) return; } display_at_given_level(node->left, level - 1); display_at_given_level(node->right, level - 1);
Assume if you have only one node, and the level is 1.
Then it will satisfy the if condition and print the node value.
Suppose,
Now you have a tree as below and level is 2:
First you go to root node, from there you will recursively call “display_at_given_level” for the left node while reducing the given level.
Now, the if condition is met, and you will print the left node.
Similarly, you will call “display_at_given_level” for the right node while reducing the given level.
Now, the if condition is met, and you will print the right node.
Solution in C++
#include <iostream> 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 display_at_given_level(Node* node, int level) { //base case if (node == NULL) { return; } //base case if(level == 1) { cout<<node->data << " "; return; } display_at_given_level(node->left, level - 1); display_at_given_level(node->right, level - 1); } 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); int level = 2; cout<<"Solution = " <<endl; display_at_given_level(root, level); return 0; }
Output:
Solution = 10 25