Question:
Given a binary tree root node, get the level of the node.
Example:
Consider the image given below
Image 1
If the given node is “25” level is 2
If the given node is “15” level is 3
Steps to get the level of a given node:
1. If the node is null, return 0.
2. If node’s data matches, then return the value.
3. If not, recursively call the left sub tree,
4. If key is not found in left sub tree, then call recursively call right sub tree.
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;
}
};
int get_level_of_node(Node *node, int data, int level)
{
if (node == NULL)
return 0;
if (node -> data == data)
return level;
int down_level = get_level_of_node(node -> left, data, level + 1);
if (down_level != 0)
return down_level;
down_level = get_level_of_node(node->right, data, level + 1);
return down_level;
}
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 node = 18;
cout<<"\n The node" <<node << " is found at "<< get_level_of_node(root, node, 1)<<endl ;
return 0;
}
Output:
The node18 is found at 3